How to globally replace a forward slash in a JavaScript string?

后端 未结 10 1942
逝去的感伤
逝去的感伤 2020-11-28 22:05

How to globally replace a forward slash in a JavaScript string?

相关标签:
10条回答
  • 2020-11-28 22:37

    Use a regex literal with the g modifier, and escape the forward slash with a backslash so it doesn't clash with the delimiters.

    var str = 'some // slashes', replacement = '';
    var replaced = str.replace(/\//g, replacement);
    
    0 讨论(0)
  • 2020-11-28 22:38

    This is Christopher Lincolns idea but with correct code:

    function replace(str,find,replace){
        if (find != ""){
            str = str.toString();
            var aStr = str.split(find);
            for(var i = 0; i < aStr.length; i++) {
                if (i > 0){
                    str = str + replace + aStr[i];
                }else{
                    str = aStr[i];
                }
            }
        }
        return str;
    }
    

    Example Usage:

    var somevariable = replace('//\\\/\/sdfas/\/\/\\\////','\/sdf','replacethis\');
    

    Javascript global string replacement is unecessarily complicated. This function solves that problem. There is probably a small performance impact, but I'm sure its negligable.

    Heres an alternative function, looks much cleaner, but is on average about 25 to 20 percent slower than the above function:

    function replace(str,find,replace){
        if (find !== ""){
            str = str.toString().split(find).join(replace);
        }
        return str;
    }
    
    0 讨论(0)
  • 2020-11-28 22:40

    You can create a RegExp object to make it a bit more readable

    str.replace(new RegExp('/'), 'foobar');
    

    If you want to replace all of them add the "g" flag

    str.replace(new RegExp('/', 'g'), 'foobar');
    
    0 讨论(0)
  • 2020-11-28 22:46

    This has worked for me in turning "//" into just "/".

    str.replace(/\/\//g, '/');
    
    0 讨论(0)
  • 2020-11-28 22:49

    Is this what you want?

    'string with / in it'.replace(/\//g, '\\');
    
    0 讨论(0)
  • 2020-11-28 22:49

    You need to wrap the forward slash to avoid cross browser issues or //commenting out.

    str = 'this/that and/if';
    
    var newstr = str.replace(/[/]/g, 'ForwardSlash');
    
    0 讨论(0)
提交回复
热议问题