How to cut string after comma and letters befor numbers

Viewed 350

I have a string

var numb = "R$ 2000,15"

I would like to cut two last numbers and comma,and R$ with space, to get result => 2000.

I tried with regex: (?!\d{1,5}),(?:\d{2}) and it takes result: R$ 2000. So now I would like to remove R$ with space.

Any help?

5 Answers

Try this regex, it should do the trick:

/^R\$\s(\d+)((\,\d{2})?)$/

To use it, you can replace like this:

let result = myNumber.replace(/^R\$\s(\d+)((\,\d{2})?)$/, "$1");

Note that each group between parentheses will be captured by your regex for replacement, so if you want the set of numbers before the comma you should use the corresponding group (in this case, 1). Also note that you should not put your regex between quotes.

You can simply split on , and then split on space

var numb = "R$ 2000,15"
let commaSplitted = numb.split(',', 1)[0]  // split by `,`
let final = commaSplitted.split(' ')       // split by space
console.log(final) 


Or you can use match

enter image description here

let numb = "R$ 2000,15"
let num = numb.match(/^R\$\s*([^,]+)/)[1]

console.log(num)

You could do it this way if you'd like by capturing the different groups and then outputting the desired group.

The three capture groups match:

  • $1 = "R$ "
  • $2 = Anything
  • $3 = ",NN" (where NN is two numbers)

const num = "R$ 2000,15";
const exp = new RegExp(/^(R\$\s)(.*)(,\d{2})$/);

document.write(num.replace(exp, "$2"));

how about this,

  var str = "R$ 2000,15";
  var res = str.split(" ");
  res=res[1].split(",");
  res[0]

in this case res[0] is what you looking for, it is working but it may not be the good practice.

Try this regular expression:

var numb = "R$ 2000,15"

numb = numb.replace(/([A-Za-z]+\W+\s{1})([0-9]*)\W+[a-zA-Z0-9]*/, "$2");

console.log(numb);

It removes all letters and symbols and one space in front of the digits

and

all trailing symbols and letters and numbers from its behind

and will give middle number.

Related