简体   繁体   中英

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>');

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM