根據一條線:
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', '');
如何替代所有事件?
当前回答
while (str.indexOf('abc') !== -1)
{
str = str.replace('abc', '');
}
其他回答
首頁 〉外文書 〉文學 〉文學 〉In string first element search and replace
此分類上一篇: 開發人員: 開發人員: 開發人員: 開發人員: 開發人員: 開發人員: 開發人員: 開發人員: 開發人員: 開發人員: 開發人員: 開發人員:
在线全球搜索和替换
var str = '[{"id":1,"name":"karthikeyan.a","type":"developer"}' var j = str.replace(/\"\][g,'[').replace(/\]\"/g,']'); console.log(j,'//global search and replace')
添加 /g
document.body.innerHTML = document.body.innerHTML.replace('hello', 'hi');
到
// Replace 'hello' string with /hello/g regular expression.
document.body.innerHTML = document.body.innerHTML.replace(/hello/g, 'hi');
G 意味着全球性
以下功能为我工作:
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");
简单地复制并将此代码插入您的浏览器控制台进行测试。
在最受欢迎的浏览器的最新版本中,您可以使用 ReplaceAll 如下:
let result = "1 abc 2 abc 3".replaceAll("abc", "xyz");
// `result` is "1 xyz 2 xyz 3"
但是,请检查我可以使用或其他兼容性表,首先确保您针对的浏览器首先添加了支持。
对于 Node.js 和旧/非当前浏览器的兼容性:
注意:不要在性能关键代码中使用下列解决方案。
作为一个简单的字体字符串的常规表达的替代品,您可以使用
str = "Test abc test test abc test...".split("abc").join("");
一般模式是
str.split(search).join(replacement)
这通常比在某些情况下更快,而不是使用替代所有和一个常见的表达式,但这似乎不再是现代浏览器的情况。
基准: https://jsben.ch/TZYzj
结论:
如果你有一个性能关键的使用案例(例如,处理数百条线),使用常规表达方法,但对于大多数典型的使用案例,这很好不需要担心特殊的字符。
while (str.indexOf('abc') !== -1)
{
str = str.replace('abc', '');
}