使用正则表达式突出显示文本中的链接

时间:2010-12-22 07:03:06

标签: javascript

您好我正在尝试使用RegEx突出显示文本中的链接,为此我尝试使用match()方法和replace()方法,   但是我没有得到它。任何人都可以帮助我。

<head runat="server">
    <title></title>
               <script type="text/javascript" >

        function findReplace() {
            var srcString = document.getElementById('new').innerHTML;
            var pattern = new RegExp("<[^<]+</a>", 'ig');
            var newString = srcString.match(pattern);
            for (var i = 0; i < newString.length; i++) {
              var replaced = srcString.replace(pattern, '<div style="background-color: yellow; display: inline; font-weight: bold;"> ' + newString[i] + ' </div>')

            document.getElementById('new').innerHTML = replaced

        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <input type='button'  id='btn'value='Match' onclick="findReplace()"  />
    <div id='new'>
    Finally we  have succeeded! <a href='#'>Remember</a> that if you just want to replace one word,
     you should use a string or normal regular expression as your searchFor parameter. However, 
     if you want to replace <a href='#'>google</a> be sure to write a <a href='#'>regularexpression</a> and append a little g at the end!
     </div>
    </form>
</body>
</html>

2 个答案:

答案 0 :(得分:2)

这将是一种不同类型的解决方案,可以摆脱正则表达式......

function highlightLinks () {
  //Get div id
  divElement = document.getElementById('new');

  //Get links in div
  var links = divElement.getElementsByTagName('a');

  //Change link styles
  for (var i=0, end=links.length; i<end; i++) {
    links[i].style.backgroundColor = 'red';
    links[i].style.display= 'inline';
    links[i].style.fontWeight= 'bold';
  }
}

或者jQuery等价物......

$("#div > a").css({'background-color':'red', 'font-weight':'bold', 'display':'inline'});

抱歉,我无法测试其中任何一个,但机器人应该可以工作。如果我不对,请纠正我......;)

答案 1 :(得分:1)

根据您的工作,这是一个解决方案:

function findReplace() {

     var pattern = new RegExp("(<a[^<]+</a>)", 'ig');
     document.getElementById('new').innerHTML = document.getElementById('new').innerHTML.replace(pattern, '<div style="background-color: yellow; display: inline; font-weight: bold;">$1</div>');
 }

如果我是你,我会使用带有document.getElementsByTagName('a')的DOM而不是Regex + innerHTML属性,你的正则表达式将不匹配:

<a href="efefe.html"><strong>okokok</strong></a>