Ad

About Regular Expressions In Js

- 1 answer

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!!!

Ad

Answer

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.

Ad
source: stackoverflow.com
Ad