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

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

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

相关标签:
10条回答
  • 2020-11-28 22:52
    var str = '/questions'; // input: "/questions"
    while(str.indexOf('/') != -1){
       str = str.replace('/', 'http://stackoverflow.com/');
    }
    alert(str); // output: "http://stackoverflow.com/questions"
    

    The proposed regex /\//g did not work for me; the rest of the line (//g, replacement);) was commented out.

    0 讨论(0)
  • 2020-11-28 22:57

    Without using regex (though I would only do this if the search string is user input):

    var str = 'Hello/ world/ this has two slashes!';
    alert(str.split('/').join(',')); // alerts 'Hello, world, this has two slashes!' 
    
    0 讨论(0)
  • 2020-11-28 22:58

    Hi a small correction in the above script.. above script skipping the first character when displaying the output.

    function stripSlashes(x)
    {
    var y = "";
    for(i = 0; i < x.length; i++)
    {
        if(x.charAt(i) == "/")
        {
            y += "";
        }
        else
        {
            y+= x.charAt(i);
        }
    }
    return y;   
    }
    
    0 讨论(0)
  • 2020-11-28 23:01

    The following would do but only will replace one occurence:

    "string".replace('/', 'ForwardSlash');
    

    For a global replacement, or if you prefer regular expressions, you just have to escape the slash:

    "string".replace(/\//g, 'ForwardSlash');
    
    0 讨论(0)
提交回复
热议问题