JavaScript Non-regex Replace

后端 未结 4 1749
旧时难觅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:24

    I had exactly the same problem searching for a non-regex javascript string replace() method. My solution was to use a combination of split() and join():

    "some text containing regex interpreted characters: $1.00".split("$").join("£");
    

    which gives:

    "some text containing regex interpreted characters: £1.00"

    compare with replace():

    "some text containing regex interpreted characters: $1.00".replace(new RegExp("$"),"£")
    

    which bizarrely gives:

    "some text containing regex interpreted characters: $1.00£"

    0 讨论(0)
  • 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;
    };
    }
    
    0 讨论(0)
  • i may be misunderstanding your question, but javascript does have a replace()

    var string = '@!#$123=%';
    var newstring = string.replace('@!#$123=%', 'hi');
    

    edit: (see comments) the 5th edition does seem to have this info in it, although it doesn't show up when i link directly to it. here's the relevant part:

    The replace( ) method performs a search-and-replace operation. It takes a regular expression as its first argument and a replacement string as its second argument. It searches the string on which it is called for matches with the specified pattern. If the regular expression has the g flag set, the replace( ) method replaces all matches in the string with the replacement string; otherwise, it replaces only the first match it finds. If the first argument to replace( ) is a string rather than a regular expression, the method searches for that string literally rather than converting it to a regular expression with the RegExp( ) constructor, as search( ) does.

    0 讨论(0)
  • 2021-02-19 08:43

    Try this:

    function replaceAllTemp(str,find, replace) { 
    var ignoreCase=true;
    var _token;
    var token=find;
    var newToken=replace;
    var i = -1;
    
    if ( typeof token === "string" ) {
    
        if ( ignoreCase ) {
    
            _token = token.toLowerCase();
    
            while( (
                i = str.toLowerCase().indexOf(
                    token, i >= 0 ? i + newToken.length : 0
                ) ) !== -1
            ) {
                str = str.substring( 0, i ) +
                    newToken +
                    str.substring( i + token.length );
            }
    
        } else {
            return this.split( token ).join( newToken );
        }
    
    }
    return str;
    };
    
    0 讨论(0)
提交回复
热议问题