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,
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, theiflag 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 afterhref=: