Javascript Regex:如何用正则表达式加粗特定单词? [英] Javascript Regex: How to bold specific words with regex?
本文介绍了Javascript Regex:如何用正则表达式加粗特定单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给针和大海捞针......我想在针头周围加上粗体标签。那么我将使用什么正则表达式与replace()?我希望SPACE成为分隔符,我希望搜索不区分大小写
Given a needle and a haystack... I want to put bold tags around the needle. So what regex expression would I use with replace()? I want SPACE to be the delimeter and I want the search to be case insensitive
所以说针是牛而干草堆是
so say the needle is "cow" and the haystack is
cows at www.cows.com, milk some COWS
将变为
<b>cows</b> at www.cows.com, milk some <b>COWS</b>
关键字也应该有空格,所以如果关键字是谁是mgmt。 ..
also keywords should be able to have spaces in it so if the keyword is "who is mgmt"...
great band. who is mgmt btw?
会变成
great band. <b>who is mgmt</b> btw?
谢谢
推荐答案
这是一个正在执行你正在寻找的正则表达式:
Here is a regex to do what you're looking for:
(^|\s)(cows)(\s|$)
在JS中,替换是这样的:
In JS, replacement is like so:
myString.replace(/(^|\s)(cows)(\s|$)/ig, '$1<b>$2</b>$3');
在可重复使用的功能中整齐地包装:
Wrapped up neatly in a reusable function:
function updateHaystack(input, needle) {
return input.replace(new RegExp('(^|\\s)(' + needle + ')(\\s|$)','ig'), '$1<b>$2</b>$3');
}
var markup = document.getElementById('somediv').innerHTML;
var output = updateHaystack(markup, 'cows');
document.getElementById('somediv').innerHTML = output;
这篇关于Javascript Regex:如何用正则表达式加粗特定单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文