0

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)}`;
   }
}
3
  • ok , so where exactly are you implementing this? Commented Sep 6, 2020 at 16:59
  • 2
    please add the wanted result and your try. Commented Sep 6, 2020 at 17:00
  • Edited answer for clarity. Commented Sep 6, 2020 at 17:12

2 Answers 2

5

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);

Sign up to request clarification or add additional context in comments.

2 Comments

Can you explain the second argument in replace?
it takes the string for each replacement and $& is the matched value, all connected digits in this case.
2

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"));

5 Comments

Can you explain a little more? Esp. the $1?
the first digits have no 'p'.
@pianoman102 The regex [-,] matches a - or , this character is placed in group 1 by surrounding it with parentheses. $1 will replace the match with the contents of group 1 the p behind $1 adds a p behind the match.
$1 is a special replacement pattern in javascript String.replace() that inserts the first parenthesized submatch string in this case [,-]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.