0

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\.*$]/,''))

1 Answer 1

2

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, ''));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.