开发者

problem with regex replacement

I am trying to highlight the word that has been passed in using regex & css. But something seems to have gone wrong. can anyone please help me? $1 doesn't seem to work here as its not replacing with the word.

 <head>
<title>Example</title>

<style type="text/css">
  .highlight{
    color: maroon;
    font-size: 22px;
  }

</style>
<script type="text/javascript" src="../scripts/jquery-1.4.js"></script>
<script type="text/javascript">
function getSentence(word) {
var sentence="here is the text";

if (sentence.toLowerCase().indexOf(word.toLowerCase())!=-1) {
    sentence=sentence.replace(new RegExp('\\b'+(word)+'\\b', 'g'), '<span class="highlight">\$1</span>');

    $("#placeholder").append("<h3>"+sentence+"</h3><br/>");

    }
    }
</script&开发者_运维技巧gt;

<form>
  <div>
    <a onclick=getSentence('text');>text</a>
  </div>
   <div id="placeholder"></div>
</form>


You're not setting any capture groups, so you should use $& instead of $1 in your replace method.

See example →


The capture brackets in your regular expression are in the wrong place. At the moment the brackets disappear as they are not literal but merely has a grouping function. Your regex should work if you place the brackets in the quotes like so:

'\\b(' + word + ')\\b'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜