根據一條線:
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', '');
如何替代所有事件?
当前回答
我喜欢这个方法(看起来有点干净):
text = text.replace(new RegExp("cat","g"), "dog");
其他回答
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
我建议通过将其附加到原型链上,为线类添加一个全球方法。
String.prototype.replaceAll = function(fromReplace, toReplace, {ignoreCasing} = {}) { return this.replace(new RegExp(fromReplace, ignoreCasing ? 'ig': 'g'), toReplace);}
它可以用作:
'stringwithpattern'.replaceAll('pattern', 'new-pattern')
与常规表达的i旗案例不敏感
console.log('App started'.replace(/a/g, '')) // Result: "App strted"
console.log('App started'.replace(/a/gi, '')) // Result: "pp strted"
// Try this way
const str = "Test abc test test abc test test test abc test test abc";
const result = str.split('abc').join('');
console.log(result);
可以用常见的表达方式实现这一点,有几种可以帮助某人:
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?]