Rafee Rafee - 4 months ago 7
Javascript Question

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

Answer

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;
}

Comments