JavaScript - The correct way to replace the character "\" charcter with "/" in RegExp

I defined a function in JavaScript that replaces everything - , _ , @ , # , $ and \ (they are possible separators) with / (a valid separator).

My goal is any line, for example "1394_ib_01#13568" convert to "1394/ib/01/13568"

 function replaceCharacters(input) { pattern_string = "-|_|@|#|$|\u005C"; // using character Unicode //pattern_string = "-|_|@|#|$|\"; // using original character //pattern_string = "-|_|@|#|$|\\"; // using "\\" //pattern_string = "\|-|_|@|#|$"; // reposition in middle or start of string pattern = new RegExp(pattern_string, "gi"); input = input.replace(pattern, "/"); return input; } 

My problem is that the line with the \ character is not valid for sending the results of the function.

I tried to use Unicode \ in the definition template, or use \\\ instead. I also replaced it with a template string. But in any of these problems the problem was not resolved, and the browser returned an incorrect result or other error, for example:

 SyntaxError: unterminated parenthetical ---> in using "\u005C" SyntaxError: \ at end of pattern ---> in using "\\" Invalid Result: broken result in 2 Line or replace with undefined character based on input string (the character after "\" determine result) ---> in reposition it in middle or start of pattern string 
+7
javascript jquery regex
source share
1 answer
 var pattern_string = "-|_|@|#|\\$|\\\\"; 

You need to break out with a slash once for the pattern, so it will try to match the letter character:

 \\ 

Then print each slash for the string literal:

 "\\\\" 

Also note that I added escape for $ . To exactly match the dollar sign, it must also be escaped, since it usually represents an anchor for the "end of line / line".


You can also use a Regex literal to avoid a string using only the escape sequences needed for the template:

 var pattern = /-|_|@|#|\$|\\/gi; 

And, since you only match single characters, you can use a character class instead of alternation :

 var pattern = /[ -_@ #\$\\]/gi; 

(Just be careful with the placement - here. It's fine, like the first character in a class, but can represent a range of characters when placed in the middle. You can also avoid this to make sure t represents the range.)

+8
source share

All Articles