Q:

replace HTML text with incrementing numbers in javascript

I have a bunch of text with no HTML, and I'm trying to find all replace all instances of String with <span id="x">String</span>
The catch is I'm trying to increment x every time to get a bunch of uniquely identifiable spans rather then identical ones.
I have no problem getting all instances of String, but for the life of me I can't get the increment to work. All help I can find seems to be directed towards doing the opposite of this.
Any ideas what I can do or where else to turn for help?
EDIT:
This is targeting a div with ID 'result' that contains only text.
    var target = "String";
    var X = //the number I was trying to increment
    var re = new RegExp(" " + target + " ","g");
    document.getElementById('result').innerHTML = document.getElementById('result').innerHTML.replace(re, '<span id="' + X + '">' + target + '</span>');

A:

I'm guessing you are using a regex, which is fine, but you can specify a function as the second parameter to replace and do your logic there.
The MDN documentation for doing this is here - https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter
You could use something like this:
http://jsfiddle.net/gjrCN/2/
function replacer(orig, target) {
    var x = 0;
    var re = new RegExp(target, "g");
    var ret = orig.replace(re, function (match) {
        return "<span id='" + (++x) + "'>" + match + "</span>";
    });
    return ret;
}

var example = "String Stringasdf String2344 String";
var replaced = replacer(example, "String");
console.log(replaced);

You can change ++x to x++ if you want the counting to start at 0 instead of 1.

