I defined a function in JavaScript that replace all -
, _
, @
, #
, $
and \
(they are possible separators) with /
(valid separator).
My goal is any string like "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 when a string with \
character send to function result is not valid.
I tried use Unicode of \
in define pattern, Or use \\\
instead of it. Also I replaced position of it in pattern string. But in any of this situation, problem wasn't solved and browser return invalid result or different error such as:
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
var pattern_string = "-|_|@|#|\\$|\\\\";
You have to escape the slash once for the pattern, so it'll try to match the literal character:
\\
Then, escape each slash again for the string literal:
"\\\\"
Also note that I added an escape for the $
. To match a dollar sign literally, it'll needs to be escaped as well, since it normally represents an anchor for the "end of the line/string."
You can also use a Regex literal to avoid the string, using only the escape sequences necessary for the pattern:
var pattern = /-|_|@|#|\$|\\/gi;
And, as you're matching only single characters, you can use a character class instead of alternation:
var pattern = /[-_@#\$\\]/gi;
(Just be careful with the placement of the -
here. It's fine as the first character in the class, but can represent a range of characters when placed in the middle. You can also escape it to ensure it doesn't represent a range.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With