0

Am in a process of writing a javascript to replace a text within [] to a html link. But am stuck at generating a regular expression to match any string that is in [] and then replace it with a hyperlink.

Below is my code snippet that i have tried:

<html>
<head>
</head>
<body id="body">

Hello World [1234]<br>
[322]<br>
Hello
</body>
</html>


<script type="text/javascript">
var bodyText=document.getElementById('body').innerHTML;
var pattern = "\[(.*?)\]";
var replaceText = "<a href="www.mysite.com">Pradeep</a>";
document.getElementById('body').innerHTML = bodyText.replace(pattern/gi, replaceText);
</script>

Can anyone please suggest me a best way to do it

Thanks,

2 Answers 2

2

If you have a string representing a regexp, you have to call new RegExp(str) to build a regexp from it, but you can just make a regexp literal here. Also, the i flag is not necessary since nothing in your regexp refers to letters. And, you don't use the capturing groups so you can eliminate them as well. Lastly, you need to escape the quotes in the string because the interpreter now thinks your strings ends after href=:

var bodyText = document.getElementById('body').innerHTML;
var pattern = /\[.*?\]/g;
var replaceText = "<a href=\"www.mysite.com\">Pradeep</a>";
document.getElementById('body').innerHTML = bodyText.replace(pattern, replaceText);
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot, it worked fine. Am now facing an other challenge. Some parts of my html code has the following lines: <div class="action-body flooded"><p>(In <span class="error">&#91;82681&#93;</span>) refs <a href="/browse/AGLBD-16096" title="GlobalTestSuite tracking">AGLBD-16096</a><br/></div>
I have to get the number with-in the [] and then replace it with a hyperlink. I have tried using document.getElementsByClassName('error') but its not working. how can I make it work? and i would also need to itirate in a loop to replace all such numbers if there are more than one in []. e.g: [123] [234] [345]...
1

I tried \[[^\]]+\] as regexp and got the right output:

var s = 'Hello World [1234]<br>[322]<br>';
s = s.replace(/\[[^\]]+\]/ig, '<a href="http://www.mysite.com">Pradeep</a>');
// output
// Hello World <a href="http://www.mysite.com">Pradeep</a><br><a href="http://www.mysite.com">Pradeep</a><br>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.