0

I have various {{ context }} in an html doc:

<p>Lorem ipsum dolor sit amet, {{ context_1  }} consectetur adipiscing elit, sed do eiusmod tempor 
incididunt ut labore et dolore magna aliqua. {{ context_2 }} Ut enim ad minim veniam.<p>

How can I add a <span> class around all the variables in curly brackets to give

<p>Lorem ipsum dolor sit amet, <span>{{ context_1 }}</span> consectetur adipiscing elit, sed do eiusmod tempor 
incididunt ut labore et dolore magna aliqua. <span>{{ context_2 }}</span> Ut enim ad minim veniam.<p>
0

1 Answer 1

1

You can use the overload of .replace (MDN) to specify a regular expression.

Combine with .html() to get and set the html.

There are various different ways to use replace with a regex, here's a couple:

.replace(/{{.*}}/g, "<span>$&</span>")
.replace(/({{.*}})/g, "<span>$1</span>")
.replace(/{{(.*)}}/g, "<span>$1</span>")  //if you also want to remove the `{{}}`

$("p").html((i, html) => {
  return html.replace(/({{.*}})/g, "<span>$1</span>")
});
p>span { color: pink }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Lorem ipsum dolor sit amet, {{ context_1  }} consectetur adipiscing elit, sed do eiusmod tempor 
incididunt ut labore et dolore magna aliqua. {{ context_2 }} Ut enim ad minim veniam.</p>
<p>Lorem ipsum dolor sit amet, {{ context_1  }} consectetur adipiscing elit, sed do eiusmod tempor 
incididunt ut labore et dolore magna aliqua. {{ context_2 }} Ut enim ad minim veniam.</p>

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

5 Comments

Thanks, how would I exclude {{ content }} in a tag element, e.g. <a href="{{ content }}"></a>?
Change the regex: , "<a href='$1'>$1</a>"
Thanks, wouldn't that just wrap the result in <a> not exclude results within <a>?
You'll need to provide an example output for what "exclude results" means
Ah, you mean, if the text is <p>Lorem ipsum <a href='{{context1}}'>dolor</a></p> - in that case the same regex, but instead of $("p").html loop through all the children elements that are just text elements.

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.