0

I'm trying to write two functions:

  • first method tests for a match in a string (like test())
  • second method replaces keywords

Simply regex (like \bkeyword\b) works, but it replaces keywords inside HTML tags (e.g class, alt) and URL anchors. How should I do this? I can not use JavaScript libraries.

EDIT: I would like replace only first match and only match on exact-matches.

Thanks

tomys
  • 1
  • 1
  • ya..regex works! but you tried something? any code ? that will be great! – Vikas Arora Nov 30 '13 at 17:51
  • 5
    regex parsing HTML -> [TH̘Ë͖́̉ ͠P̯͍̭O̚​N̐Y̡ H̸̡̪̯ͨ͊̽̅̾̎Ȩ̬̩̾͛ͪ̈́̀́͘ ̶̧̨̱̹̭̯ͧ̾ͬC̷̙̲̝͖ͭ̏ͥͮ͟Oͮ͏̮̪̝͍M̲̖͊̒ͪͩͬ̚̚͜Ȇ̴̟̟͙̞ͩ͌͝S̨̥̫͎̭ͯ̿̔̀ͅ](http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags) – adeneo Nov 30 '13 at 17:52
  • If you've some HTML in a string, you better to create a temporary HTMLElement, and set its innerHTML to that string. Then manipulate the textContents of the newly created elements. If you need a HTML as string, get it out of the temporary element, or append the element to the page. – Teemu Nov 30 '13 at 17:58

2 Answers2

1

If you use DOM methods you can iterate through the text nodes with a replace function, keeping out of the markup tags-

function swapText(node, find, replace){
    var fun= function(n){
        n.data= n.data.replace(find, replace);
    }
    if(node){
        node= node.firstChild;
        while(node!= null){
            if(node.nodeType== 3)fun(node);
            else swapText(node, find, replace);
            node= node.nextSibling;
        }
    }
}

swapText(document.body, /e/g, 'E');

kennebec
  • 102,654
  • 32
  • 106
  • 127
0

Suppose you have an HTML like:

var text = '<span class="myclass"> span text </span>';

Then you just need to find all the occurrences of the text between html tag and you can replace it by using an anonymous function as a second parameter to replace.

Here i am using WORD as a replacement of span

var result = text.replace(/<[^>]+>|(span)/g, function(p1, p2) { 
     return ((p2==undefined)||p2=='')?p1:"WORD"; 
}); 

console.log(result)

Also, check the syntax of replace:

newstring = str.replace(regexp|substr, newSubStr|function[,   flags]);

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

Zeeshan Abbas
  • 821
  • 6
  • 20