Fred J.
Fred J.

Reputation: 6029

remove unwanted groups of characters from string using regex

Given: 1999 some text here 1.3i [more]
Needed: some text here

The following regex - replace(/[\d{4} |\d\.*$]/,'') - failed, it just removed the first digit. Any idea why and how to fix it?

var s = "1999 some text here 1.3i [more]"
console.log(s.replace(/[\d{4} |\d\.*$]/,''))

Upvotes: 0

Views: 769

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626794

The regex you have removes the first digit only because it matches just 1 char - either a digit, {, 4, }, space, |, ., * or $ (as [...] formed a character class), just once (there is no global modifier).

You may use

/^\d{4}\s+|\s*\d\..*$/g

See the regex demo

Basically, remove the [ and ] that form a character class, add g modifier to perform multiple replacements, and add .* (any char matching pattern) at the end.

Details:

First alternative:
- ^ - start of string
- \d{4} - 4 digits
- \s+ - 1+ whitespaces

Second alternative:
- \s* - 0+ whitespaces
- \d - a digit
- \. - a dot
- .* - any 0+ chars up to...
- $ - the end of the string

var rx = /^\d{4}\s+|\s*\d\..*$/g;
var str = "1999 some text here 1.3i [more]";
console.log(str.replace(rx, ''));

Upvotes: 2

Related Questions