正则表达式替换的问题

时间:2011-03-25 06:51:52

标签: javascript regex

我正在尝试突出使用正则表达式& CSS。但似乎出现了问题。谁能帮帮我吗? $ 1在这里似乎不起作用,因为它没有取代单词。

 <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>

  

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

2 个答案:

答案 0 :(得分:0)

您没有设置任何捕获组,因此您应该在替换方法中使用$&而不是$1

See example →

答案 1 :(得分:0)

正则表达式中的捕获括号位于错误的位置。目前,括号消失,因为它们不是字面的,而只是具有分组功能。如果将括号放在引号中,那么你的正则表达式应该可以工作:

'\\b(' + word + ')\\b'
相关问题