根據一條線:
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', '');
如何替代所有事件?
当前回答
以下功能为我工作:
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");
简单地复制并将此代码插入您的浏览器控制台进行测试。
其他回答
截至2020年8月,为ECMAScript提供了一个阶段4的提议,该提议将替代All 方法添加到 String。
它现在支持Chrome 85+,Edge 85+,Firefox 77+,Safari 13.1+。
使用方式与替代方法相同:
String.prototype.replaceAll(searchValue, replaceValue)
下面是使用例子:
'Test abc test test abc test.'.replaceAll('abc', 'foo'); // -> 'Test foo test test foo test.'
它在大多数现代浏览器中支持,但有多元化:
核心JS Es-Shims
它支持在V8发动机背后一个实验旗帜 - 和谐 - 带 - 替代。
要编码一个URL,你不应该只考虑空间,而是用编码URI正确地转换整个行。
encodeURI("http://www.google.com/a file with spaces.html")
要得到:
http://www.google.com/a%20file%20with%20spaces.html
while (str.indexOf('abc') !== -1)
{
str = str.replace('abc', '');
}
添加 /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 意味着全球性
重复,直到你已经取代了所有:
const regex = /^>.*/im;
while (regex.test(cadena)) {
cadena = cadena.replace(regex, '*');
}