字符串中有多个查找和替换
Multiple find and replace in string
我有一个字符串,看起来像这样,
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>')
解释:
{(project|object)}
:匹配用大括号括起来的project
或object
字符串。将字符串添加到第一个捕获的组中(.*?)
:懒惰地匹配任何东西以满足条件- 这里的
{'/'1}
:'1
是第一个捕获组的反向参考。因此,如果第一个捕获的组包含object
,则这将匹配{/object}
gi
:g
是匹配所有可能的字符串。i
将不区分大小写地匹配- 替换部分中的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/
相关文章:
- 在DOM中查找一个模式并替换它's的内容使用jquery
- 需要URL模板占位符查找和替换功能的输入
- 原型JS查找跨度并替换文本
- javascript:查找/替换regexp帮助-粗体、斜体和特定字符
- 查找并替换特定字符串
- Javascript 条件查找/替换
- jQuery 查找/替换大量文本
- 在jQuery中查找/替换HTML标签之间的字符串
- 如何用javascript查找/替换html
- 如何只在字符串的开头部分查找/替换不区分大小写
- 查找替换html使用javascript
- 使用Javascript查找替换URL的短部分
- 独特的查找/替换系统不工作
- 在画布上查找-替换
- 纯Javascript -查找/替换DOM中的单词列表
- Javascript查找替换
- 使用Regexp查找/替换文本
- 基本查找替换词
- 正则表达式或jQuery来查找/替换迭代计数
- 在Texareas内查找/替换WYSIWYG