0

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

1 Answer 1

3

You can use

var text = "sdasd #ELEMENT1# asdasd #ELEMENT2#";

text = text.replace(/#(.*?)#/g, '<button>$1</button>');
snippet.log(text)
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

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

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.