JavaScript Non-regex Replace

后端 未结 4 1725
旧时难觅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: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;
    };
    

提交回复
热议问题