Hướng dẫn thực hành RegEx trong JS

Siêu™
Siêu™
Sep 5, 2018 · 2 min read
Keep calm and regex

Khi bạn bắt đầu học RegEx bạn sẽ thấy nó là 1 chuỗi ký tự vô nghĩa, bạn cảm thấy lúng túng với 1 cú pháp khó hiểu nhưng lại vô cùng hữu ích

Khi hiểu về RegEx bạn sẽ cảm thấy mình pro hơn =)). Nhưng để trông pro cần đi từ cơ bản đã… let’s go..

Regular Expressions là gì?

RegEx được hiểu đơn giản là 1 pattern cho phép bạn kiểm tra 1 chuỗi ký tự như email, mật khẩu.. khớp với pattern đã được định nghĩa.

Tạo 1 Regular Expressions như thế nào?

Có 2 cái để tạo RegEx trong JS

- Regular Expression Constructor

Syntax new RegExp(pattern[, flags])

Ví dụ:

var regexConst = new RegExp('abc');

Sử dụng dấu /

Syntax: /pattern/flags

Ví dụ

var regexLiteral = /abc/

Oh, flags ko bắt buộc à? Yes, sir!

Nếu muốn sử dụng dấu / như 1 phần của RegEx thì chỉ cần thêm dấu \

Bạn sẽ thấy thắc mắc với 2 tùy chọn trên thì nó khác nhau như thế nào?

Với RegEx Constructor bạn có thể tạo các RegEx dynamic và yên tâm kết quả trả về của 2 kiểu Regex đều là regex object.

Nguồn https://blog.bitsrc.io/a-beginners-guide-to-regular-expressions-regex-in-javascript-9c58feb27eb4

Siêu™

Written by

Siêu™

I am a PHP Developer. And I want to become Superman.

VNEXT LIFE

Stories from Vnexter

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade