Home > Blockchain >  How can I change the comma separating two currencies in a string?
How can I change the comma separating two currencies in a string?

Time:12-21

If I have a string value: let x = '$2,500,$3,500'

What would be the best way in JavaScript to return

x = '$2,500|$3,500'

to the user?

I have tried messing around with some regex but am unsure how to either capture or ignore the numeric value in between the $ and ,

I feel like there has to be a simple way of doing this that I am missing. Please let me know if you need any more details and thanks in advance.

CodePudding user response:

Use a non-word-boundary \B

 let result = str.replace(/,\B/g, '|');

That matches between two characters of the \W character class (that contains , and $). Note that it matches also between two characters of the \w class.

CodePudding user response:

You could take a looking ahead and replace the comma, followed by dollar sign.

const
    replace = string => string.replace(/,(?=\$)/g, '|'),
    string = '$2,500,$3,500';

console.log(replace(string));

CodePudding user response:

A solution without regex:

x = '$2,500,$3,500'
let res = x.replace(",$", "|$");
console.log(res)

And if you have multiple values:

x = '$2,500,$3,500,$123,456'
let res = x.replaceAll(",$", "|$");
console.log(res)

  • Related