简体   繁体   中英

replace odd and even occurence with html javascript

I am trying to replace ` ticks with html code in a string.

var str = "this `code` and `here`"

my expected output

"this code and here"

What i am trying to do is below .

  1. get the positions with ticks in a string
  2. replace those ticks with span html based on odd and even occurence.

not sure, i couldnt get expected and my browser gets hang. and when i debug it. i see there is no index for string to replace.

String.prototype.replaceAt = function(index, character) {
    return this.substr(0, index) + character + this.substr(index+character.length);
}

var pos = [];
for (var i = 0; i < str.length; i++) {
    if (str[i] === "`") {
        pos.push(i);
    }
}


            if (pos.length > 1) {
                for (var j = pos.length; j > 0; j--) {
                    var index = pos[j];
                    var spanHtml = '';

                    if (j % 2 == 0) {
                        spanHtml = "<span class='code'>"
                    } else {
                        spanHtml = "</span>";
                    }

                    str = str.replaceAt(index, spanHtml);
                }
            }

You can use String.prototype.replace() with RegExp

/(`\w+`)/g 

String.prototype.slice() with parameters 1, -1 to slice string within backtick

`

characters

 var str = "this `code` and `here`"; var res = str.replace(/(`\\w+`)/g, function(match) { return "<span class='code'>" + match.slice(1, -1) + "</span>" }); document.body.insertAdjacentHTML("beforeend", res); 
 .code { background: turquoise; } 

Use the JavaScript replace method.

var str = "this `code` and `here`";

var newStr = str.replace("`", "");
  1. scope of var i is wider then you think, so pos.push(i) will have them all same at the end
  2. replaceAt appends incorrect ending
  3. replaceAt shifts rest of the string invalidating positions you found

I believe you wanted something along these lines:

var str = "this `code` and `here`"

String.prototype.replaceAt = function(index, character) {
    return this.substr(0, index) + character + this.substr(index+1);
}

var pos = [];
var count = 0;
for (var i = 0; i < str.length; i++) {
    if (str[i] === "`") {
        var index = i;
        var spanHtml = '';
        if (count % 2 == 0) {
            spanHtml = "<span class='code'>"
        } else {
            spanHtml = "</span>";
        }
        count++;
        str = str.replaceAt(index, spanHtml);
        i+= spanHtml.length -1; // correct position to account for the replacement
    }
}

console.log(str)

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