I am a noob with js and a was wondering if I can search and replace characters in a string using regular expressions but with some rules like for ex:
Let's say I want to search and replace every whitespace that is before a semicolon, the code will be something like this:
But when I do this, of course that the ';' it's gonna be replaced by the "". My question is: is there a way of deleting all whitespaces before a semicolon but without deleting the semicolon?
Thanks for your answers!!!
You are replacing
\s*; with empty string
"". You need to replace it with a
If you want to do it multiple times in the string, then use the global modifier:
Check this demo.
Your suffix being a semicolon, you can simply replace the whole match with a semicolon, which will preserve it. And since you probably want your program to do this several times on the same string, I'd suggest using the global flag. Also you want to replace at least one space character.
Which gives us