hi i am trying to highlight links in a text using RegEx ,For this I tried with match() method and replace() method, but i didn't get it.plz any one can help me.
<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 y开发者_Python百科our 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>
Here would be a different kind of solution that would get rid of the regexp...
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';
}
}
Or a jQuery equivalent...
$("#div > a").css({'background-color':'red', 'font-weight':'bold', 'display':'inline'});
Sorry, I couldn't test either of these, but bot should work. Correct me if I'm incorrect... ;)
based on your work, here is a solution :
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>');
}
If I were you, I would use the DOM with document.getElementsByTagName('a') instead of Regex + innerHTML property and your regex won't match :
<a href="efefe.html"><strong>okokok</strong></a>
精彩评论