mustapha george
mustapha george

Reputation: 621

javascript replace characters

I want to replace all occurent of "-", ":" characters and spaces from a string that appears in this format:

"YYYY-MM-DD HH:MM:SS"

something like:

var date = this.value.replace(/:-/g, "");

Upvotes: 6

Views: 14923

Answers (4)

FishBasketGordo
FishBasketGordo

Reputation: 23142

You can use either a character class or an | (or):

var date = "YYYY-MM-DD HH:MM:SS".replace(/[:-\s]/g, '');

var date = "YYYY-MM-DD HH:MM:SS".replace(/:|-|\s/g, '');

Upvotes: 1

zzzzBov
zzzzBov

Reputation: 179264

The regex you want is probably:

/[\s:-]/g

Example of usage:

"YYY-MM-DD HH:MM:SS".replace(/[\s:-]/g, '');

[] blocks match any of the contained characters.

Within it I added the \s pattern that matches space characters such as a space and a tab \t (not sure if you want tabs and newlines, so i went with tabs and skipped newlines).

It seems you already guessed that you want the global match which allows the regex to keep replacing matches it finds.

Upvotes: 1

gen_Eric
gen_Eric

Reputation: 227310

/:-/g means ":" followed by "-". If you put the characters in [] it means ":" or "-".

var date = this.value.replace(/[:-]/g, "");

If you want to remove spaces, add \s to the regex.

var date = this.value.replace(/[\s:-]/g, "");

Upvotes: 2

Gabi Purcaru
Gabi Purcaru

Reputation: 31574

You were close: "YYYY-MM-DD HH:MM:SS".replace(/:|-/g, "")

Upvotes: 7

Related Questions