字符串中有多个查找和替换

Multiple find and replace in string

本文关键字:查找 替换 字符串      更新时间:2024-06-05

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

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

虽然这感觉不是特别简洁,但有更好的方法吗?

您可以使用单个RegEx

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

解释:

  1. {(project|object)}:匹配用大括号括起来的projectobject字符串。将字符串添加到第一个捕获的组中
  2. (.*?):懒惰地匹配任何东西以满足条件
  3. 这里的{'/'1}:'1是第一个捕获组的反向参考。因此,如果第一个捕获的组包含object,则这将匹配{/object}
  4. gi:g是匹配所有可能的字符串。i将不区分大小写地匹配
  5. 替换部分中的CCD_ 12和CCD_

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


RegEx可以简称为

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

regex是您的朋友:

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)

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

http://handlebarsjs.com/

$.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/