JavaScript Non-regex Replace

后端 未结 4 1727
旧时难觅i
旧时难觅i 2021-02-19 08:08

Do any of the existing JavaScript frameworks have a non-regex replace() function, or has this already been posted on the web somewhere as a one-off function?

<
4条回答
  •  情书的邮戳
    2021-02-19 08:27

    You can do it with or without ignoring case sensitivity.
    Sadly, JavaScript's indexOf doesn't take locale vs. invariant as argument, so you'll have to replace toLowerCase with toLocaleLowerCase if you want to preserve culture-specifity.

    function replaceAll(str, find, newToken, ignoreCase)
    {
        var i = -1;
    
        if (!str)
        {
            // Instead of throwing, act as COALESCE if find == null/empty and str == null
            if ((str == null) && (find == null))
                return newToken;
    
            return str;
        }
    
        if (!find) // sanity check 
            return str;
    
        ignoreCase = ignoreCase || false;
        find = ignoreCase ? find.toLowerCase() : find;
    
        while ((
            i = (ignoreCase ? str.toLowerCase() : str).indexOf(
                find, i >= 0 ? i + newToken.length : 0
            )) !== -1
        )
        {
            str = str.substring(0, i) +
                newToken +
                str.substring(i + find.length);
        } // Whend 
    
        return str;
    }
    

    or as prototype:

    if (!String.prototype.replaceAll ) {  
    String.prototype.replaceAll = function (find, replace) {
        var str = this, i = -1;
    
        if (!str)
        {
            // Instead of throwing, act as COALESCE if find == null/empty and str == null
            if ((str == null) && (find == null))
                return newToken;
    
            return str;
        }
    
        if (!find) // sanity check 
            return str;
    
        ignoreCase = ignoreCase || false;
        find = ignoreCase ? find.toLowerCase() : find;
    
        while ((
            i = (ignoreCase ? str.toLowerCase() : str).indexOf(
                find, i >= 0 ? i + newToken.length : 0
            )) !== -1
        )
        {
            str = str.substring(0, i) +
                newToken +
                str.substring(i + find.length);
        } // Whend 
    
        return str;
    };
    }
    

提交回复
热议问题