根據一條線:
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', '');
如何替代所有事件?
当前回答
我使用p来存储以前的回归替换结果:
function replaceAll(s, m, r, p) {
return s === p || r.contains(m) ? s : replaceAll(s.replace(m, r), m, r, s);
}
它将取代链 s 的所有事件,直到它是可能的:
replaceAll('abbbbb', 'ab', 'a') → 'abbbb' → 'abbb' → 'abb' → 'ab' → 'a'
要避免无限旋转,我检查替代r是否包含一匹匹匹配m:
replaceAll('abbbbb', 'a', 'ab') → 'abbbbb'
其他回答
这是最快的版本,不使用常规表达式。
修订 JSperf
replaceAll = function(string, omit, place, prevstring) {
if (prevstring && string === prevstring)
return string;
prevstring = string.replace(omit, place);
return replaceAll(prevstring, omit, place, string)
}
它几乎比分裂和合并方法快两倍。
正如在评论中所指出的那样,如果你的错误变量包含位置,就不会工作,因为它总是能够取代另一个出现的词。
有另一个JSperf与我的回归替换的变量,它走得更快(http://jsperf.com/replace-all-vs-split-join/12)!
2017 年 7 月 27 日更新: 看起来 RegExp 现在在最近发布的 Chrome 59 中具有最快的性能。
方法1
尝试执行一个常见的表达式:
“测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试
方法2
与ABC分开并加入空空间。
“测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试ABC测试
替换单一引用:
function JavaScriptEncode(text){
text = text.replace(/'/g,''')
// More encode here if required
return text;
}
截至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发动机背后一个实验旗帜 - 和谐 - 带 - 替代。
可以用常见的表达方式实现这一点,有几种可以帮助某人:
var word = "this,\\ .is*a*test, '.and? / only / 'a \ test?";
var stri = "This is a test and only a test";
取代所有非阿尔法字符,
console.log(word.replace(/([^a-z])/g,' ').replace(/ +/g, ' '));
Result: [this is a test and only a test]
用一个空间替换多个连续空间,
console.log(stri.replace(/ +/g,' '));
Result: [This is a test and only a test]
取代所有 * 字符,
console.log(word.replace(/\*/g,''));
Result: [this,\ .isatest, '.and? / only / 'a test?]
取代问题标志(?)
console.log(word.replace(/\?/g,'#'));
Result: [this,\ .is*a*test, '.and# / only / 'a test#]
取代引用标志,
console.log(word.replace(/'/g,'#'));
Result: [this,\ .is*a*test, #.and? / only / #a test?]
要取代所有“字符”,
console.log(word.replace(/,/g,''));
Result: [this\ .is*a*test '.and? / only / 'a test?]
替换一个特定的词,
console.log(word.replace(/test/g,''));
Result: [this,\ .is*a*, '.and? / only / 'a ?]
取代Backslash。
console.log(word.replace(/\\/g,''));
Result: [this, .is*a*test, '.and? / only / 'a test?]
以替代前滑,
console.log(word.replace(/\//g,''));
Result: [this,\ .is*a*test, '.and? only 'a test?]
替换所有空间,
console.log(word.replace(/ /g,'#'));
Result: [this,\#.is*a*test,####'.and?#/#only#/#####'a##test?]
替换点,
console.log(word.replace(/\./g,'#'));
Result: [this,\ #is*a*test, '#and? / only / 'a test?]