The text below is selected, press Ctrl+C to copy to your clipboard. (⌘+C on Mac) No line numbers will be copied.
Guest
Javascript How to insert links into text from a list of words in an array, case insensitive Regexp - working example
By Guest on 30th October 2022 09:28:04 PM | Syntax: JAVASCRIPT | Views: 212



New Paste New paste | Download Paste Download | Toggle Line Numbers Show/Hide line no. | Copy Paste Copy text to clipboard
  1. <div id="content"> it's not really simple. It's really simple in every other language. It's ridiculously complex in JS, where you have in and of that can both be used and do different things. Then you also have forEach and the ugly and annoying index based looping. Every other modern language makes looping over a collection easy and straightforward with no surprises or confusion. JS could, too, but it doesn't!</div>
  2.  
  3. <script>
  4. function keywordconvert(str, p1, offset, s)  {
  5.       return "<a href=\"link.php?keyword="+encodeURIComponent(p1)+"\">"+p1+"</a>";
  6. }
  7.  
  8. function insertLink(keyword) {
  9.    var content = document.getElementById("content");
  10.    var re = new RegExp("("+keyword+")","ig");
  11.   content.innerHTML = content.innerHTML.replace(re, keywordconvert);
  12. }
  13.  
  14. var myStringArray = ["language","complex", "Collection"];
  15. var arrayLength = myStringArray.length;
  16. for (var i = 0; i < arrayLength; i++) {
  17.     insertLink(myStringArray[i]);
  18. }
  19.  
  20.  
  21. </script>
  22.  
  23.  
  24. //adapted from http://jsfiddle.net/JHHzU/2/














  • Recent Pastes