views:

22

answers:

1

I have an html that has a lot of the following:

<TD CLASS="broke"> - WF-1234567 -  </TD>
<TD CLASS="broke"> - WF-1111111 -  </TD>
<TD CLASS="broke"> - WF-7654321 -  </TD>

I want to make a javascript bookmarklet to replace all the 7-digit numbers with a hyperlink. How does one do this?

My attempt with many things wrong....

javascript:
var match=new RegExp("(- WF-....... - Review)","ig");
var x = document.getElementsByClassName("broke").innerHTML;
x=x.replace(match,<a href="www.blah.com/"+7digitSubsetofMatch>7digitlink</a>);
document.getElementsByClassName("browseItemLocation").innerHTML=x;
+1  A: 

getElementsByClassName returns a list, not a single item with innerHTML available. you'll have to iterate over the list and handle each item individually.

javascript:(function(){

var elements = document.getElementsByClassName("broke");

for (var j = 0; j < elements.length; j++) {

to find and replace the number, you'll need to adjust your regex grouping- right now you're capturing a larger string without a way to get the digits. you do this by moving the parentheses to immediately surround the number

    var pattern = new RegExp("WF-(\\d+)", "ig");
    var match = elements[j].innerHTML.match(pattern);

if you had a successful match, then match[0] will be the whole string matched and match[1] will be the digits

you can't write literal html in javascript- it has to be a string.

    var x = elements[j].innerHTML.replace(match[1],
        '<a href="www.blah.com/' + match[1] + '">' + match[1] + '</a>');

then you cna replace your original html.

    elements[j].innerHTML = x;
}

})()

I don't know what your last line does but it seems unnecessary.

lincolnk
Good answer Hulk Hogan
Drew