根據一條線:
s = "Test abc test test abc test test test abc test test abc";
这似乎只是在上面的行中删除ABC的第一次出现:
s = s.replace('abc', '');
如何替代所有事件?
根據一條線:
s = "Test abc test test abc test test test abc test test abc";
这似乎只是在上面的行中删除ABC的第一次出现:
s = s.replace('abc', '');
如何替代所有事件?
当前回答
如果使用图书馆是您的选择,那么您将获得与图书馆功能一起进行的测试和社区支持的好处。
// Include a reference to the string.js library and call it (for example) S.
str = S(str).replaceAll('abc', '').s;
其他回答
下面是工作代码与原型:
String.prototype.replaceAll = function(find, replace) {
var str = this;
return str.replace(new RegExp(find.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1"), 'g'), replace);
};
基于定期表达的实施
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.replace(new RegExp(search, 'g'), replacement);
};
String.prototype.replaceAll = function(search, replacement) {
var target = this;
return target.split(search).join(replacement);
};
看看这个参数运行这两个实施对彼此。
正如 @ThomasLeduc 和其他人在下面的评论中所指出的那样,如果搜索包含某些字符,这些字符在常规表达式中被保留为特殊字符,则可能会出现常规表达式的实施问题。
MDN 还提供了一个实施,以逃避我们的线条. 如果它也被标准化为 RegExp.escape(str),但不幸的是,它不存在:
function escapeRegExp(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); // $& means the whole matched string
}
点击此处,我肯定会帮助你:
<!DOCTYPE html>
<html>
<body>
<p>Click the button to do a global search and replace for "is" in a string.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = 'Is this "3" dris "3"?';
var allvar= '"3"';
var patt1 = new RegExp( allvar, 'g' );
document.getElementById("demo").innerHTML = str.replace(patt1,'"5"');
}
</script>
</body>
</html>
这里是JSFiddle的链接。
看看这个答案,也许它会帮助,我在我的项目中使用它。
function replaceAll(searchString, replaceString, str) {
return str.split(searchString).join(replaceString);
}
replaceAll('abc', '',"Test abc test test abc test test test abc test test abc" ); // "Test test test test test test test test "
以下功能为我工作:
String.prototype.replaceAllOccurence = function(str1, str2, ignore)
{
return this.replace(new RegExp(str1.replace(/([\/\,\!\\\^\$\{\}\[\]\(\)\.\*\+\?\|\<\>\-\&])/g,"\\$&"),(ignore?"gi":"g")),(typeof(str2)=="string")?str2.replace(/\$/g,"$$$$"):str2);
} ;
现在,请称这些功能如下:
"you could be a Project Manager someday, if you work like this.".replaceAllOccurence ("you", "I");
简单地复制并将此代码插入您的浏览器控制台进行测试。