根據一條線:
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', '');
如何替代所有事件?
当前回答
表演
今天 2019 年 12 月 27 日 我在 macOS v10.13.6 (High Sierra) 上进行测试,以便选择的解决方案。
结论
基于分合(A、B)或替换(C、D)的解决方案是基于时间的快速解决方案(E、F、G、H)是缓慢的 - 通常是小线的4倍缓慢,长线的约3000倍缓慢。
str.split`abc`.join``
细节
此分類上一篇
短字 - 55 个字符
您可以在您的机器上运行测试 此处. Chrome 的结果:
此分類上一篇
重复解决方案 RA 和 RB 提供
对于1M字符,他们甚至打破了Chrome
此分類上一篇
我试图为其他解决方案进行1M字符的测试,但E、F、G、H需要这么长时间,浏览器要求我打破脚本,所以我将测试行缩短到275K字符。
测试中使用的代码
其他回答
要编码一个URL,你不应该只考虑空间,而是用编码URI正确地转换整个行。
encodeURI("http://www.google.com/a file with spaces.html")
要得到:
http://www.google.com/a%20file%20with%20spaces.html
2020年8月
不再有常见的表达式
const str = “测试 abc 测试 abc 测试 abc 测试 abc”; const modifiedStr = str.replaceAll('abc', ''); console.log(modifiedStr);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/参考/Global_Objects/String/replaceAll
如果使用图书馆是您的选择,那么您将获得与图书馆功能一起进行的测试和社区支持的好处。
// Include a reference to the string.js library and call it (for example) S.
str = S(str).replaceAll('abc', '').s;
可替代的独特价值
String.prototype.replaceAll = function(search_array, replacement_array) { // var target = this; // search_array.forEach(function(substr, index) { if (typeof replacement_array[index]!= "undefined") { target = target.replace(new RegExp(substr, 'g'), replacement_array[index] ) }); // return target; }; // Use: var replacedString = "This topic commented o
可以用常见的表达方式实现这一点,有几种可以帮助某人:
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?]