Select Page
JavaScript code to encapsulate {{}} with span elements
JavaScript code to encapsulate {{}} with span elements

Problem

For examples: if a div tag has content “{{1}}{{2}}” and i want to encapsulate all {{}} like “<span class=”sample-1″>{{1}}</span><span class=”sample-2″>{{2}}</span>” how to do it with JavaScript.

Solution

You can achieve this by using JavaScript and DOM manipulation methods. Here is an example code snippet that should accomplish this. The following script use replace method to find all instances of {{…}} using a regular expression, and replace them with a new span element with the appropriate class name. The $& in the replacement string includes the matched text in the output.

HTML

<div id="my-div">{{1}}{{2}}{{3}}{{4}}</div>

CSS

// JavaScript code to encapsulate {{}} with span elements
var div = document.getElementById("my-div");
var content = div.innerHTML;
content = content.replace(/{{(.*?)}}/g, '<span class="sample-$1">$&</span>');
div.innerHTML = content;

DEMO

See the Pen Untitled by Puneet Sharma (@webdevpuneet) on CodePen.