We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
StackOverflow: https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string-in-javascript
Regular Expression Based Implementation
String.prototype.replaceAll = function(search, replacement) { var target = this; return target.replace(new RegExp(search, 'g'), replacement); };
Split and Join (Functional) Implementation
String.prototype.replaceAll = function(search, replacement) { var target = this; return target.split(search).join(replacement); };
The text was updated successfully, but these errors were encountered:
但是正则表达式的实现其实是有漏洞的,当 search 包含正则表达式的特殊字符时会出错。MDN 上有一个方法帮我们把一个 string 转化成 new RegExp 的参数。
new RegExp
function escapeRegExp(string) { return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string }
Sorry, something went wrong.
No branches or pull requests
StackOverflow: https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string-in-javascript
Regular Expression Based Implementation
Split and Join (Functional) Implementation
The text was updated successfully, but these errors were encountered: