-3

I have a string like this:

var str = "A A A A A";

how do I replace a specific A with something else?

Eg: replace 3rd A to:

var str = "A A 00 A A";

Of the 1st, 2nd, etc.. ?

2
  • google 'javascript replace nth occurrence', there are so many variants on stackoverflow alone that i don't even know which one to say this is a duplicate of. Commented Jun 29, 2015 at 17:04
  • possible duplicate of Replacing the nth instance of a regex match in Javascript Commented Jun 29, 2015 at 17:05

2 Answers 2

1

I would split the str, replace whatever index, then join back

var str = "A    A    A    A    A";
var sp=str.split('   ');
var ind=2;
sp[ind]='00';
console.log(sp.join('   '));

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

Comments

0

I prefer to use regular expression, here is the answer:

newValue = str.replace(/(([^A]*A){2}[^A]*)A/g, '$100');

Notes: {2} is the number of the occurrence we want to replace.

$100 here we specify which is the new string we want to place after the $1

Comments

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.