Victor Amorim
Victor Amorim

Reputation: 13

Replace() with Split()

I need to enter a "0" in case there's only one digit after the comma, how does replace() work in this situation?

var a = "2x 250,5";

console.log(a.replace(a.split(",")[1], a.split(",")[1] + 0));

//expected result
// 2x 250,50

//Output
//2x 2500,5

Upvotes: 1

Views: 854

Answers (4)

Mert Çelik
Mert Çelik

Reputation: 382

var a = "2x 250,1",
splitvar = ","
a.split(splitvar)[1].length==1 && (a = a.replace(splitvar+a.split(splitvar)[1], ","+a.split(splitvar)[1] + 0))
console.log(a);

Upvotes: 0

Vahid Alimohamadi
Vahid Alimohamadi

Reputation: 5858

let a = "2x 250,0";

console.log([a.split(','), a.split(',').pop().length===1 ? '0':null].join(''));

Upvotes: 1

Yosef Tukachinsky
Yosef Tukachinsky

Reputation: 5895

try

a.replace(/,\d$/, x => x+'0');

var tests = [
  '2x 250,0',
  '2x 200,03',
  '2x 511,0',
  '2x 413,3'
]
function addZero(str){
  return str.replace(/,\d$/, x => x+'0');
}
tests.forEach(str => console.log(addZero(str)));

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386654

You could search for a comma, digit and end of string and add a zero at the end.

var a = "2x 250,0";

console.log(a.replace(/,\d$/, '$&0'));

Upvotes: 4

Related Questions