Skip to content
New issue

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

javascript String.prototype.replaceAll #199

Open
teazean opened this issue Dec 28, 2017 · 1 comment
Open

javascript String.prototype.replaceAll #199

teazean opened this issue Dec 28, 2017 · 1 comment

Comments

@teazean
Copy link
Owner

teazean commented Dec 28, 2017

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);
};
@teazean
Copy link
Owner Author

teazean commented Dec 28, 2017

但是正则表达式的实现其实是有漏洞的,当 search 包含正则表达式的特殊字符时会出错。MDN 上有一个方法帮我们把一个 string 转化成 new RegExp 的参数。

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant