Reputation: 5351
I want to replace one or more question marks with a replacement (template language), like that:
var translation = "this is a ???";
console.log(translation.replace(/(\?+)/g, "replacement")); //this is a replacement
But now, I recently ran into an issue where the question mark was actually intended as a question and should not be escaped. I decided to go for the ~
as escaping character, so this should not be escaped:
var translation = "this should not be escaped, cause it's a question, is it~?";
console.log(translation.replace(/[^~](\?+)/g, "replacement"));
Works so far. However, if I go with multiple question marks (requirement for the template syntax), I end up with crap:
var translation = "this should not be escaped, cause it's a question, is it~???";
console.log(translation.replace(/[^~](\?+)/g, "replacement"));
//this should not be escaped, cause it's a question, is it~replacement <-- ???
Any suggestion on how to do that? A classical \
as escaping character would make me happier than the ~
but I ran into issues with that as well.
Upvotes: 0
Views: 52
Reputation: 782673
Use negative lookbehind:
translation.replace(/(<!~)\?+/g, "replacement");
Upvotes: 1
Reputation: 191819
~
should probably be used to escape only a single character (which I think would be expected). Users of the template could write ~?~?~?
to escape multiple characters.
As for the replacement, [^~]
still selects a character.
translation.replace(/([^~])\?+/g", "$1replacement")
The $1
will insert the selected character back again
Upvotes: 1