Hi 🤓 Cảm ơn bạn đã ghé thăm blog này, nếu những bài viết trên blog giúp ích cho bạn. Bạn có thể giúp blog hiển thị quảng cáo bằng cách tạm ngừng ad blocker 😫 và để giúp blog duy trì hoạt động nếu bạn muốn.
Cảm ơn bạn!
Trong bài viết này, chúng ta cùng tìm hiểu về method replaceAll
trong Javascript để xem method này có chức năng gì nhé!
replaceAll[] method
Để hiểu hơn về replaceAll[]
chúng ta cùng tìm hiểu về method replace[]
trước nhé.
Method replace[]
giúp chúng ta thay thế một substring nằm trong chuỗi muốn thay thế.
Ta có ví dụ như sau:
'homiedevhomiedev'.replace['homiedev', 'blog'];
// bloghomiedev'
Ở ví dụ trên, ta thực hiện thay thế substring là homiedev
thành blog
. Tuy nhiên khi
sử dụng replace[]
ta chỉ có thể thay thế được chuỗi homiedev
ở lần xuất hiện đầu tiên và các lần xuất hiện tiếp theo sẽ bị bỏ qua.
Trong trường hợp bạn muốn thay thế tất cả các chuỗi, chúng ta có thể sử dụng regular expressions
như sau:
'homiedevhomiedev'.replace[/homiedev/g, 'blog'];
// blogblog
Sử dụng regular expressions
giúp chúng ta có thể get hoặc replace các substring trong các trường hợp phức tạp. Còn trong trường hợp trên ta có thể sử dụng một cách đơn giản hơn đó là dùng method replaceAll[]
.
Chúng ta đơn giản chỉ cần như sau:
'homiedevhomiedev'.replaceAll['homiedev', 'blog'];
// blogblog
Như bạn thấy ở trên, kết quả ta nhận được giống như khi sử dụng regular expressions
, bạn có thể sử dụng một trong những cách này để thay thể chuỗi theo ý muốn ^^.
Kết luận
Như vậy là chúng ta đã tìm hiểu xong method replaceAll[]
, hy vọng bài viết giúp ích cho các bạn.
Chúng ta sẽ gặp lại sau trong các bài viết sắp tới nhé!
Một số bài viết JavaScript nên đọc:
- Callback Function trong JavaScript là gì? tại sao lại được sử dụng nhiều như vậy?
- Tìm hiểu về Memoization trong JavaScript
- Tìm hiểu về method startsWith JavaScript thông qua ví dụ đơn giản
- some js là gì? Tìm hiểu về method some trong JavaScript
About Me
Hi, I'm @devnav. Một người thích chia sẻ kiến thức, đặc biệt là về Frontend 🚀. Trang web này được tạo ra nhằm giúp các bạn học Frontend hiệu quả hơn 🎉😄.
Chúc các bạn tìm được kiến thức hữu ích trong blog này 😁😁.
The replaceAll[]
method returns a new string with all matches of a pattern
replaced by a replacement
. The pattern
can be a string or a RegExp
, and the replacement
can be a string or a function to be called for each match. The original string is left unchanged.
Try it
Syntax
replaceAll[pattern, replacement]
Parameters
pattern
Can be a string or an object with a Symbol.replace
method — the typical example being a
regular expression. Any value that doesn't have the Symbol.replace
method will be coerced to a string.
If pattern
is a regex, then it must have the global [g
] flag set, or a
TypeError
is thrown.
replacement
Can be a string or a function. The replacement has the same semantics as that of String.prototype.replace[]
.
Return value
A new string, with all matches of a pattern replaced by a replacement.
Exceptions
TypeError
Thrown if the pattern
is a regex that does not have the global [g
] flag set [its flags
property does not contain "g"
].
Description
This method does not mutate the string value it's called on. It returns a new string.
Unlike replace[]
, this method would replace all occurrences of a string, not just the
first one. This is especially useful if the string is not statically known, as calling the RegExp[]
constructor without escaping special characters may unintentionally change its semantics.
function unsafeRedactName[text, name] {
return text.replace[new RegExp[name, 'g'], '[REDACTED]'];
}
function safeRedactName[text, name] {
return text.replaceAll[name, '[REDACTED]'];
}
const report = "A hacker called ha.*er used special characters in their name to breach the system.";
console.log[unsafeRedactName[report, "ha.*er"]]; // "A [REDACTED]s in their name to breach the system."
console.log[safeRedactName[report, "ha.*er"]]; // "A hacker called [REDACTED] used special characters in their name to breach the system."
If pattern
is an object with a
Symbol.replace
method [including RegExp
objects], that method is called with the target string and replacement
as arguments. Its return value becomes the return value of replaceAll[]
. In this case the behavior of replaceAll[]
is entirely encoded by the @@replace
method, and therefore will have the same result as replace[]
[apart from the extra input validation that the
regex is global].
If the pattern
is an empty string, the replacement will be inserted in between every UTF-16 code unit, similar to split[]
behavior.
"xxx".replaceAll["", "_"]; // "_x_x_x_"
For more information about how regex properties [especially the
sticky flag] interact with replaceAll[]
, see RegExp.prototype[@@replace][]
.
Examples
Using replaceAll[]
'aabbcc'.replaceAll['b', '.'];
// 'aa..cc'
Non-global regex throws
When using a regular expression search value, it must be global. This won't work:
'aabbcc'.replaceAll[/b/, '.'];
// TypeError: replaceAll must be called with a global RegExp
This will work:
'aabbcc'.replaceAll[/b/g, '.'];
"aa..cc"
Specifications
ECMAScript Language Specification # sec-string.prototype.replaceall |
Browser compatibility
BCD tables only load in the browser