1

I'm looking for some REGEX or some other way in JS how to remove decimal numbers from string.

example input:

Mazda 6 2.0 Skyactiv-G Wagon 2018 - Startstop.sk - TEST
Mercedes C63 AMG Sound REVVING 6,3l V8 

example output:

Mazda 6 Skyactiv-G Wagon 2018 - Startstop.sk - TEST
Mercedes C63 AMG Sound REVVING l V8 

Everywhere I look people want to keep both integers and decimals and just remove strings. But I want to keep all integers just remove decimals (with comma, or dot.)

I tried something like:

var string = "Mazda 6 2.0 Skyactiv-G Wagon 2018 - Startstop.sk - TEST"
parseFloat(string.match(/[\d\.]+/))
// Result is 6

But this actually just again remove everything exept integers.

Andurit
  • 5,612
  • 14
  • 69
  • 121

3 Answers3

2

You can try \s\d*\.\d+\s

Where

\s - matches any whitespace character

\d* - matches digit (equal to [0-9]) between zero and unlimited times

\. - matches the character . literally

d+ - matches digit (equal to [0-9]) between one and unlimited times

var string = `Mazda 6 2.0 Skyactiv-G Wagon 2018 - Startstop.sk - TEST
Mercedes C63 AMG Sound REVVING 6,3l V8`
console.log(string.replace(/\s\d*\.\d+\s|\s\d*,\d+/gm, ' '));
Mamun
  • 66,969
  • 9
  • 47
  • 59
2

You can match bot a dot and a comma using a character class [,.] and match 1 or more digits before and after it.

Instead of using string.match you can use string.replace and using an empty string in the replacement.

Matching optional leading whitespace chars to prevent the double space gaps after removing only the digits:

\s*\d+[.,]\d+

Regex demo

var string = "Mazda 6 2.0 Skyactiv-G Wagon 2018 - Startstop.sk - TEST"
string = string.replace(/\s*\d+[.,]\d+/g, "");
console.log(string);

Or matching 1 or more times a dot or comma followed by 1 or more digits, you can use a repeated non capturing group:

\s*\d+(?:[.,]\d+)+
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
0
var string = "Mazda 6 2.0 Skyactiv-G Wagon 2018 - Startstop.sk - TEST";
regex = /\d+(\.\d+)/g;
string = string.replace(regex, "");
console.log(string);

result :

Mazda 6  Skyactiv-G Wagon 2018 - Startstop.sk - TEST

explain :

\d :  Matches any digit character (0-9).
+ :   Match 1 or more of the preceding token.
[\.,] : Match "." character  or "," character.
aziz k'h
  • 775
  • 6
  • 11