-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.. ?

Cœur
  • 37,241
  • 25
  • 195
  • 267
JeffVader
  • 702
  • 2
  • 17
  • 33
  • 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. – hubson bropa Jun 29 '15 at 17:04
  • possible duplicate of [Replacing the nth instance of a regex match in Javascript](http://stackoverflow.com/questions/36183/replacing-the-nth-instance-of-a-regex-match-in-javascript) – hubson bropa Jun 29 '15 at 17:05

2 Answers2

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('   '));
depperm
  • 10,606
  • 4
  • 43
  • 67
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

Chris Rosete
  • 1,240
  • 15
  • 13