TAGS :Viewed: 7 - Published at: a few seconds ago

[ Multiple find and replace in string ]

I have a string that looks like this,

Joe Bloggs created the {project}Joe Project 1{/project} and created the brief {object}Brief Number 1{/object}

I want to turn this into a string of HTML that would looks like this,

Joe Bloggs created the <a href="" class="project-link">Joe Project 1</a> and created the brief <a href="" class="object-link">Brief Number 1</a>

I know I can do this,

var string = "Joe Bloggs created the {project}Joe Project 1{/project} and created the brief {object}Brief Number 1{/object}";
string.replace("{project}", "<a href='' class='project-link'>");
string.replace("{/project}", "</a>");
string.replace("{object}", "<a href='' class='object-link'>");
string.replace("{/object}", "</a>");

This does not feel particularly succinct though, is there a nicer way of doing this?

Answer 1


You can use a single RegEx

str.replace(/{(project|object)}(.*?){\/\1}/gi, '<a href="" class="$1-link">$2</a>')

Explanation:

  1. {(project|object)}: Match project or object string wrapped in curly braces. Add the string in first captured group.
  2. (.*?): Match anything lazily to satisfy the condition
  3. {\/\1}: \1 here is the back-reference of the first captured group. Thus, if the first captured group contains object this will match {/object}.
  4. gi: g is to match all possible strings. i is to match case-insensitively.
  5. $1 and $2 in the replacement part are the first and second captured groups respectively.

var str = 'Joe Bloggs created the {project}Joe Project 1{/project} and created the brief {object}Brief Number 1{/object}';

var result = str.replace(/{(project|object)}(.*?){\/\1}/gi, '<a href="" class="$1-link">$2</a>');

console.log(result);
document.body.textContent = result; // For showing result on page

document.body.innerHTML += '<hr />' + result; // For showing HTML on page


The RegEx can made short as

{((?:pro|ob)ject)}(.*?){\/\1}

Answer 2


regex is your friend:

var string = "Joe Bloggs created the {project}Joe Project 1{/project} and created the brief {object}Brief Number 1{/object}";

string = string.replace(/{\/\w+}/g, "</a>"); //with this you strip out closing tag

string = string.replace(/{(\w+)}/g, function(m,m2) {
  return "<a href='' class='" + m2 + "-link'>"
})//this part will wrap whatever inside the opening braces in to your desired markup

console.log(string)

Answer 3


There are templating libraries that exist for this purpose. Check out the handlebars templating library to get started (there are lots and lots to choose from).

http://handlebarsjs.com/

Answer 4


$.validator.format("Joe Bloggs created the {0}Joe Project 1{1} and created the brief {2}Brief Number 1{1}", "<a href='' class='project-link'>","</a>","<a href='' class='object-link'>")

Source: http://jqueryvalidation.org/jQuery.validator.format/