简体   繁体   中英

javascript to replace a text within [] with hyperlink

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, 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);

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM