/g là biểu thức chính quy giúp tác vụ dễ dàng. /g tìm kiếm toàn cục (globally). Nếu cần thay thế từ xuyên suốt mọi lần xuất hiện, /g là cần thiết.
Ví dụ thay "blue" thành "red" dùng str.replace() thường. Không có chỉ thị toàn cục, chỉ lần đầu tiên bị thay, các lần còn lại giữ nguyên. Lưu ý JS phân biệt chữ hoa thường.
Ví dụ
<html> <body> <script>
var str = "Mr Blue has a blue house and a blue car";
var res = str.replace(/blue/, "red");
document.write(res);
</script> </body> </html>
Kết quả
Mr Blue has a red house and a blue car
Với /g, tất cả "blue" thành "red".
Ví dụ
<html> <body> <script>
var str = "Mr Blue has a blue house and a blue car";
var res = str.replace(/blue/g, "red");
document.write(res);
</script> </body> </html>
Kết quả
Mr Blue has a red house and a red car