0

I want to replace something like this with jquery

['{star}'],['{heart}'],['{call}']

Whenever in BODY we got {star} , replace that with

<i class="fa fa-star"></i>

Or for {hear}{call}, etc.

How can i do this?

each element , {star} => fa fa-star, {heart}=> fa fa-heart

[EDIT SOLVED]

var str = "{heart}{star}"
var updated = str.replace(/\{([^}]+)}/g, '<i class="fa fa-$1"></i>');
document.body.innerHTML = document.body.innerHTML.replace(/\{([^}]+)}/g, '<i class="fa fa-$1"></i>');

7
  • Okay, what does your JQuery look like so far? I wont write the code for you, but you need to find the item you want, then replace it with the item in your array. Commented Apr 14, 2017 at 19:49
  • Might want to post a valid array Commented Apr 14, 2017 at 19:49
  • $('body :not(script)').contents().filter(function() { return this.nodeType === 3; }).replaceWith(function() { var finds = ['{star}','{heart}']; var finds_to = ['StarS','HeartS']; return this.nodeValue.replace(finds[i],finds_to[i]); }); Commented Apr 14, 2017 at 19:50
  • I suppose you could parse the HTML and regex replace? Commented Apr 14, 2017 at 19:50
  • 1
    As a nudge in the right direction: document.body.innerHTML = document.body.innerHTML.replace(/{star}/g, '<i class="fa fa-star"></i>'); Commented Apr 14, 2017 at 19:50

1 Answer 1

0

Simple regular expression to match anything between {}

var str = "I {heart} to eat an {apple}"
var updated = str.replace(/\{([^}]+)}/g, '<i class="fa fa-$1"></i>');
console.log(updated);

You could also replace it with ors with known strings.

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

9 Comments

thanks,it's true , but how this can find {heart} and {apple} in body content ? :(
replace the innerHTML?
yeap replace to all of HTML content
this will replace html content to heart and apple , but don't replace just {heart} and {apple} !
|

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.