[英]jQuery regex to find string by substring
On my website I have multiple occurrences of a string with always the same substring (let's say "boo-foo", "loo-foo" and "great-foo"). 在我的网站上,多次出现带有始终相同子字符串的字符串(比如说“ boo-foo”,“ loo-foo”和“ great-foo”)。
I want to replace all of those with firstpart- foo. 我想用firstpart- foo替换所有这些。 So the first part of all those should be bold.
因此,所有这些的第一部分应加粗。
Can anyone provide a regex for that in jQuery? 谁能在jQuery中提供正则表达式?
I believe it should look something like this, but with regex: 我相信它应该看起来像这样,但是使用正则表达式:
$(this).html($(this).html.replace("boo-foo","<strong>boo-</strong>foo"));
Please check this script, 请检查此脚本,
var htmlText = $('body').html();
var replaced = htmlText.replace(/([\w\d]+)\-foo/ig, "<strong>$1</strong>-foo");
$('body').html(replaced);
Fiddle: https://jsfiddle.net/o6doa4o6/ 小提琴: https : //jsfiddle.net/o6doa4o6/
Updated Fiddle to make "-" bold as well. 更新了Fiddle,使“-”也变为粗体。
https://jsfiddle.net/o6doa4o6/1/ https://jsfiddle.net/o6doa4o6/1/
$(this).html($(this).html().replace(/^(.*)\-foo$/ig,'<strong>$1</strong>-foo');
You can use the back Reference to look for the captured group and then use the string.replace
method to replace the string using a Regex. 您可以使用背面参考来查找捕获的组,然后使用
string.replace
方法使用正则表达式替换字符串。 Backreferences allows to reference the text which was previously matched by a capturing group. 反向引用允许引用先前与捕获组匹配的文本。 In javascript you can make use of
$1
to reference the first captured group. 在javascript中,您可以使用
$1
来引用第一个捕获的组。 Similarly $2, $3..
for each captured group. 同样
$2, $3..
每个捕获的组$2, $3..
Following implementation shows this behavior, excluding the Jquery part. 以下实现显示了此行为,但不包括Jquery部分。
var stringValue = `boo-foo loo-foo great-foo`; var regexToSearch = /([a-zA-Z]*)-foo/g; var result = stringValue.replace(regexToSearch, '<strong>$1</strong>-foo'); console.log(result);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.