JavaScript regex with escaped slashes does not replace

后端 未结 5 545
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-15 03:04

Do i have to escape slashes when putting them into regular expression?

myString = \'/courses/test/user\';
myString.replace(/\\/courses\\/([^\\/]*)\\/.*/, \"$         


        
相关标签:
5条回答
  • 2020-12-15 03:46

    Actually, you don't need to escape the slash when inside a character class as in one part of your example (i.e., [^\/]* is fine as just [^/]*). If it is outside of a character class (like with the rest of your example such as \/courses), then you do need to escape slashes.

    0 讨论(0)
  • 2020-12-15 03:46

    Note, that you don't have to escape / if you use new RegExp() constructor:

    console.log(new RegExp("a/b").test("a/b"))

    0 讨论(0)
  • 2020-12-15 03:51

    string.replace doesn't modify the original string. Instead, a returns a new string that has had the replacement performed.

    Try:

    myString = '/courses/test/user';
    document.write(myString.replace(/\/courses\/([^\/]*)\/.*/, "$1"));
    
    0 讨论(0)
  • 2020-12-15 04:03

    /[\/]/g matches forward slashes.
    /[\\]/g matches backward slashes.

    0 讨论(0)
  • 2020-12-15 04:08

    Your regex is perfect, and yes, you must escape slashes since JavaScript uses the slashes to indicate regexes.

    However, the problem is that JavaScript's replace method does not perform an in-place replace. That is, it does not actually change the string -- it just gives you the result of the replace.

    Try this:

    myString = '/courses/test/user';
    myString = myString.replace(/\/courses\/([^\/]*)\/.*/, "$1");
    document.write(myString);
    

    This sets myString to the replaced value.

    0 讨论(0)
提交回复
热议问题