0

I have a string:

"josh marie anne josh anne marie chloe josh anne ..."

If I found josh, I want to replace for JJJ. So I have a string replace like this:

var p = 'josh';
var username = 'JJJ';

$("#comment").val($("#comment").val().replace(p, username));

the problem is, I don't want to replace the first josh in the string... I want to choose with one to replace (the second josh in the #comment or the first josh, of the third...)

Any ideas how to choose with one to replace?

html

<textarea id=comment>josh marie anne josh anne marie chloe josh anne josh marie anne josh anne marie chloe josh anne</textarea>

https://jsfiddle.net/tbjswpLb/

RGS
  • 4,062
  • 4
  • 31
  • 67

2 Answers2

1

You can rewrite your logic like this to achive what you want,

var p = 'josh',username = 'JJJ',cnt = 0,replaceAt = 3;
var regEx = new RegExp(p,"g")

$("#comment").val($("#comment").val().replace(regEx,function(matchedString){
  return (++cnt == replaceAt) ? username : matchedString;
}));

Use the callBack function of replace to match the occurrence series.

DEMO

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
0

Answer From: jquery-find-and-replace-second-one

fiddle

Updated Scripts:

var p = 'josh';
var username = 'JJJ';

var out = replaceMatch( $("#comment").val(), p, username, 2)

$("#comment").val(out);

function replaceMatch(originalString, searchFor , replaceWith, matchNumber)
{
  var match = 0;
  return originalString.replace(searchFor, function(found){
    match++;
    return (match===matchNumber)?replaceWith:found;
  },'g');
}
Community
  • 1
  • 1
Murad Hasan
  • 9,565
  • 2
  • 21
  • 42