pianoman102
pianoman102

Reputation: 549

Insert character at every occurrence of another character in a string javascript

I have a string 3-5,10-15,20 and I want to insert p before every number. I wanted to just find each '-' and ',' and insert a 'p' after each one, and then one at the beginning. Looping over it requires manipulating the string you're looping over, which wasn't working quite well for me. I feel like this is such a simple task, but I'm getting stuck. Any help would be appreciated.

The final result should look like p3-p5,p10-p15,p20. This is what I tried:

input = `p${input}`;
for (let i = 0; i < input.length; i++) {
   if (input[i] === '-' || input[i] === ',') {
    input = `${input.slice(0, i + 1)}p${input.slice(i + 1)}`;
   }
}

Upvotes: 0

Views: 1458

Answers (2)

Nina Scholz
Nina Scholz

Reputation: 386728

You could search for digits and replace the digits with added value.

var string = '3-5,10-15,20',
    result = string.replace(/\d+/g, 'p$&');

console.log(result);

Upvotes: 4

Nicolas
Nicolas

Reputation: 8670

You could use a regex to match the - and the , character and replace them using a group.

const input = '3-5,10-15,20';

console.log(input.replace(/([-,])/g, "$1p"));

Upvotes: 2

Related Questions