1

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>');
1
  • 1
    Show us your code. Your question makes very little sense as-is. Commented Nov 29, 2012 at 1:07

2 Answers 2

4

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.

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

Comments

1

With reference to these docs.

You can pass a function to the String.replace method would allow you to increment a counter with each call and use that to set your ID:

var forReplacements = "I do like a String that's a nice long String with Strings in it";

var incrementer = (function() {
    var counter = -1;
    var fn = function(match) {
        counter++;
        return "<span id='"+counter+"'>"+match+"</span>";
    };
    fn.reset = function() {
        counter = -1;
    }
    return fn;
}());
var newString = forReplacements.replace(/String/g, incrementer )

See this fiddle to see it in action

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.