问题描述:

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:

someString.replace(/\s*;/, "");

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 ;.

Replace:

someString.replace(/\s*;/, "");

with:

someString.replace(/\s*;/, ";");

Edit:
If you want to do it multiple times in the string, then use the global modifier: someString.replace(/\s*;/g, ";");

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

someString.replace(/\s+;/g, ';');
相关阅读:
Top