I have a string like this: var text = "sdasd #ELEMENT1# asdasd #ELEMENT2#"; and I have to replace all the #ELEMENT-X# for a button and you would get something like this sdasd <button>ELEMENT1</button> asdasd <button>ELEMENT2</button>.
I have a little regex that returns an array of index of every #
var regexp = /\#/g;
var match, matches = [];
while ((match = regexp.exec(text)) != null) {
matches.push(match.index);
}
console.log(matches);
then I tried to replace the # for the and if # is odd or even, but it doesn't work as I was expected
var count=0;
var countPos=0;
var tempText='';
for(var j=0; j<text.length; j++){
for(var k=0; k<matches.length; k++){
if(j===matches[k]) {
if(count%2 !== 0){
tempText = text.substr(countPos,j);
finalText += tempText.replace("%", '<button type="button" class="btn btn-default btn-xs fx-remove" data-var-token="[%XPTO%]" contenteditable="false">')
}else{
tempText = text.substr(countPos,j);
finalText += tempText.replace("%","</button>");
}
finalText += text.substr(countPos,j);
count++;
countPos = j;
}
}
}
console.log('--------- '+finalText+' ---------------');
My finalText returns a lot more text then the original text.
What is the best approach to solve this?
Thank you