多个查找和替换字符串

时间:2016-04-12 14:03:48

标签: javascript

我有一个看起来像这样的字符串,

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

我想把它变成一个看起来像这样的HTML字符串,

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>

我知道我可以做到这一点,

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>");

但这并不是特别简洁,有没有更好的方法呢?

4 个答案:

答案 0 :(得分:3)

您可以使用单个RegEx

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

<强>解释

  1. {(project|object)}:匹配{0}包裹在花括号中的projectobject字符串。在第一个捕获的组中添加字符串。
  2. (.*?):懒洋洋地匹配任何条件以满足条件
  3. {\/\1}\1此处是第一个捕获组的反向引用。因此,如果第一个捕获的组包含object,则该匹配{/object}
  4. gig将匹配所有可能的字符串。 i是不区分大小写的。
  5. 替换部分中的
  6. $1$2分别是第一个和第二个被捕获的组。
  7. &#13;
    &#13;
    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
    &#13;
    &#13;
    &#13;

    RegEx可以缩短为

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

答案 1 :(得分:1)

正则表达式是你的朋友:

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)

答案 2 :(得分:0)

为此目的存在模板库。查看车把模板库以便开始使用(有很多可供选择)。

http://handlebarsjs.com/

答案 3 :(得分:0)

$.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'>")

来源:http://jqueryvalidation.org/jQuery.validator.format/