从段落中查找特定单词

3
我正在从段落中查找特定单词,并希望将其加粗。我已经编写了以下代码,但它无法正常工作。

var text = /Lorem/ig;
$('div')
  .filter(function() {
    return text.test($(this).text())
  }).wrap('<strong></strong>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has
  survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing
  software like Aldus PageMaker including versions of Lorem Ipsum.</div>

演示代码


你的 JSFiddle 代码中没有 .test() 方法。 - Rahul
有人能给我一个想法,为什么我的代码不起作用吗? - Rakesh Kumar
2个回答

3

这里有一个由elclanrs创建的小型插件

$.fn.wrapInTag = function(opts) {

   var tag = opts.tag || 'strong'
, words = opts.words || []
, regex = RegExp(words.join('|'), 'gi') // case insensitive
, replacement = '<'+ tag +'>Lorem</'+ tag +'>';

 return this.html(function() {
   return $(this).text().replace(regex, replacement);
  });};

// Usage
$('div').wrapInTag({
  tag: 'strong',
  words: ['Lorem']   //can be comma seprated like  ['Lorem','ipsum']
});

Working Demo


我认为你在工作演示中链接了错误的 fiddle。 - timo
如何使用多个单词...我认为通过这个代码,所有单词都将被替换为“Lorem”。 - Rakesh Kumar
那么,如果你想要逐字替换,这样是行不通的。需要修改插件。 - Milind Anantwar
请删除此注释 //可以用逗号分隔,如['Lorem', 'ipsum']。 - Rakesh Kumar

0

你可以使用正则表达式反向引用:

var text=new RegExp('(Lorem)','ig');
$('div').html($('div').html().replace(text, "<strong>$1</strong>"));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接