renathy
renathy

Reputation: 5355

remove space from string between all numbers and percentage (javascript regex)

I have to remove all spaces between number and percentage sign. String can contain all other symbols as well. Space should be removed only between number and percentage not any other symbol and percentage.

Examples:

str = "test 12 %"; // expected "test 12%"
str = "test 1.2 %"; // expected "test 1.2%"
str = "test 1,2 %   2.5  %"; // expected "test 1,2%   2.5%"
str = " % test 1,2 %   2.5  % something"; // expected " % test 1,2%   2.5% something"

I think that I have managed to create regexp that matches "decimal number with percentage sign", however, I do not know how to do "replace space in this matching number".

var r = /\(?\d+(?:\.\d+)? ?%\)? */g;

Upvotes: 2

Views: 1261

Answers (1)

ctwheels
ctwheels

Reputation: 22837

Code

See regex in use here

(\d) +(?=%)

Replacement: $1

Usage

const regex = /(\d) +(?=%)/g
const a = ['test 12 %','test 1.2 %','test 1,2 %   2.5  %',' % test 1,2 %   2.5  % something']
const subst = `$1`

a.forEach(function(str) {
  console.log(str.replace(regex, subst))
})


Explanation

  • (\d) Capture a digit into capture group 1
  • + Match one or more spaces
  • (?=%) Positive lookahead ensuring what follows is a %

Upvotes: 2

Related Questions