根據一條線:

s = "Test abc test test abc test test test abc test test abc";

这似乎只是在上面的行中删除ABC的第一次出现:

s = s.replace('abc', '');

如何替代所有事件?


当前回答

要取代所有事件,您可以在JavaScript中使用取代()或取代所有方法。

替代()方法 - 使用此方法替代所有元素,使用常规表达式作为模式找到匹配行,然后用新的行替代它。

replaceAll() 方法 - 要使用此方法取代所有元素,请使用一行或常规表达式作为模式找到相匹配的行,然后用新的行取代它。

const str = “做或不做”; const pattern = “做”; const replaceBy = “代码”; console.log(str.replaceAll(pattern, replaceBy)); const pattern2 = /do/g; console.log(str.replaceAll(pattern2, replaceBy));

其他回答

最好的解决方案,以取代我们使用的任何字符的 indexOf(),包括(),和substring()功能,以取代相匹配的行与提供的行在当前行。

String.indexOf() 函数是找到 nth 匹配指数位置. String.includes() 方法确定一个行是否可以在另一个行中找到,随时返回真实或虚假。

下面的功能允许使用任何字符. 如 RegExp 不允许某些特殊字符如 ** 和某些字符需要逃避,如 $。

String.prototype.replaceAllMatches = function(obj) { // Obj format: { 'matchkey' : 'replaceStr' }
    var retStr = this;
    for (var x in obj) {
        //var matchArray = retStr.match(new RegExp(x, 'ig'));
        //for (var i = 0; i < matchArray.length; i++) {
        var prevIndex = retStr.indexOf(x); // matchkey = '*', replaceStr = '$*' While loop never ends.
        while (retStr.includes(x)) {
            retStr = retStr.replaceMatch(x, obj[x], 0);
            var replaceIndex = retStr.indexOf(x);
            if( replaceIndex <  prevIndex + (obj[x]).length) {
                break;
            } else {
                prevIndex = replaceIndex;
            }
        }
    }
    return retStr;
};
String.prototype.replaceMatch = function(matchkey, replaceStr, matchIndex) {
    var retStr = this, repeatedIndex = 0;
    //var matchArray = retStr.match(new RegExp(matchkey, 'ig'));
    //for (var x = 0; x < matchArray.length; x++) {
    for (var x = 0; (matchkey != null) && (retStr.indexOf(matchkey) > -1); x++) {
        if (repeatedIndex == 0 && x == 0) {
            repeatedIndex = retStr.indexOf(matchkey);
        } else { // matchIndex > 0
            repeatedIndex = retStr.indexOf(matchkey, repeatedIndex + 1);
        }
        if (x == matchIndex) {
            retStr = retStr.substring(0, repeatedIndex) + replaceStr + retStr.substring(repeatedIndex + (matchkey.length));
            matchkey = null; // To break the loop.
        }
    }
    return retStr;
};

我们还可以使用常规表达式对象,以匹配文本与模式,以下是将常规表达式对象使用的功能。

String.prototype.replaceAllRegexMatches = function(obj) { // Obj format: { 'matchkey' : 'replaceStr' }
    var retStr = this;
    for (var x in obj) {
        retStr = retStr.replace(new RegExp(x, 'ig'), obj[x]);
    }
    return retStr;
};

请注意,常规表达式是没有引用的。


var str = "yash yas $dfdas.**";
console.log('String: ', str);

// No need to escape any special character
console.log('Index matched replace: ', str.replaceMatch('as', '*', 2));
console.log('Index Matched replace: ', str.replaceMatch('y', '~', 1));
console.log('All Matched replace: ', str.replaceAllMatches({'as': '**', 'y':'Y', '$':'-'}));
console.log('All Matched replace : ', str.replaceAllMatches({'**': '~~', '$':'&$&', '&':'%', '~':'>'}));

// You need to escape some special Characters
console.log('REGEX all matched replace: ', str.replaceAllRegexMatches({'as' : '**', 'y':'Y', '\\$':'-'}));

结果:

String:  yash yas $dfdas.**
Index Matched replace:  yash yas $dfd*.**
Index Matched replace:  yash ~as $dfdas.**

All Matched replace:  Y**h Y** -dfd**.**
All Matched replace:  yash yas %$%dfdas.>>

REGEX All Matched replace:  Y**h Y** -dfd**.**

str = "Test abc test test abc test test test abc test test abc"

str.split(' ').join().replace(/abc/g,'').replace(/,/g, ' ')

截至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发动机背后一个实验旗帜 - 和谐 - 带 - 替代。

要取代所有事件,您可以在JavaScript中使用取代()或取代所有方法。

替代()方法 - 使用此方法替代所有元素,使用常规表达式作为模式找到匹配行,然后用新的行替代它。

replaceAll() 方法 - 要使用此方法取代所有元素,请使用一行或常规表达式作为模式找到相匹配的行,然后用新的行取代它。

const str = “做或不做”; const pattern = “做”; const replaceBy = “代码”; console.log(str.replaceAll(pattern, replaceBy)); const pattern2 = /do/g; console.log(str.replaceAll(pattern2, replaceBy));

var myName = 'r//i//n//o//l////d';
var myValidName = myName.replace(new RegExp('\//', 'g'), ''); > // rinold
console.log(myValidName);

var myPetName = 'manidog';
var renameManiToJack = myPetName.replace(new RegExp('mani', 'g'), 'jack'); > // jackdog