0

Am now facing an other challenge. Some parts of my html code has the following lines:

<div class="action-body flooded"><p>(In <span class="error">&#91;82681&#93;</span>) refs <a href="/browse/AGLBD-16096" title="GlobalTestSuite tracking">AGLBD-16096</a><br/></div> 

I have to get the number with-in the [] and then replace it with a hyperlink. I have tried using document.getElementsByClassName('error') but its not working. how can I make it work? and i would also need to iterate in a loop to replace all such numbers if there are more than one in []. e.g: [123] [234] [345]...

This is all what I have written till now with pimvdb's help:

<script type="text/javascript"> 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); </script> 
1
  • document.body gives you the body element. What you're using looks for an element with the id body. Otherwise, this appears to work. Commented Mar 14, 2012 at 7:44

3 Answers 3

1

This JSFiddle does what you need: http://jsfiddle.net/TNyms/

Sign up to request clarification or add additional context in comments.

Comments

1

When you replace getElementById('body') with document.body, the code works for me.

var body = document.body; var link = "<a href=\"http://www.mysite.com\">Pradeep</a>"; body.innerHTML = body.innerHTML.replace(/\[.*?\]/g, link); 

That replaces all IDs in this with links:

<div class="action-body flooded"> <p>(In <span class="error">&#91;82681&#93;</span>) refs <a href="/browse/AGLBD-16096" title="">AGLBD-16096</a> <br/> </div> <div>[123][abcd]</div> <div>[456]</div> <div>[789]</div> 

Outputs:

(In Pradeep) refs AGLBD-16096

PradeepPradeep

Pradeep

Pradeep

Try it with this fiddle.

Comments

0

Your question appears to be related to what is asked in the below link. You may refer this

Replace number in a string using regex or something else

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.