0

I want to replace every occurrence of the numbers with the string: ???.

Here is an example string:

<em>Chelsea</em> 1-4 Atletico Madrid

How can I do this in JavaScript?

    <a href="https://www.google.com/url?sa=t&amp;source=web&amp;cd=9&amp;cad=rja&amp;ved=0CFEQtwIwCA&amp;url=http%3A%2F%2Fwww.whoateallthepies.tv%2Fchelsea%2F137070%2Fsuper-cup-chelsea-1-4-atletico-madrid-falcao-on-fire-as-blues-flop-in-monaco-photos-highlights.html&amp;rct=j&amp;q=chelsea&amp;ei=1odBUImpBIWA0AWM1oC4BA&amp;usg=AFQjCNEwdCCckt15XTkHSAf2fsUnGk9IJg&amp;sig2=IOrD6hfMrviW9ods0DG2dw" class="l" onmousedown="return rwt(this,'','0','','9','AFQjCNEwdCCckt15XTkHSAf2fsUnGk9IJg','IOrD6hfMrviW9ods0DG2dw','0CFEQtwIwCA',null,event)" title="Super Cup: Chelsea 1-4 Atletico Madrid – Falcao On Fire As Blues Flop In Monaco (Photos ...">Super Cup: <em>Chelsea</em> 1-4 Atletico Madrid – Falcao On <b>...</b></a>

Thanks in advance.

john_science
  • 6,325
  • 6
  • 43
  • 60

2 Answers2

1

So basically you just want the text node, and not the HTML content, to be affected by the replace.

Unfortunately there is no simple method to get text nodes, unlike getElementBy* functions, so you have to search manually:

var elems = document.getElementsByTagName('*'), l = elems.length, i,
    children, m, j;
for( i=0; i<l; i++) {
  children = elems[i].childNodes;
  m = children.length;
  for( j=0; j<m; j++) {
    if( children[j].nodeType == 3) children[j].nodeValue = children[j].nodeValue.replace(/\d+/g,'???');
  }
}
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • i just want to replace every occurence in numbers in video title by ???? https://www.google.com/search?tbm=vid&hl=en&source=hp&biw=1366&bih=557&q=chelsea&btnG=Google+Search&gbv=2&oq=&gs_l=#q=chelsea&hl=en&gbv=2&tbm=vid&source=lnt&tbs=qdr:d&sa=X&ei=HoNBUOudH-ma0QWB0IHoDg&ved=0CCEQpwUoAg&fp=1&biw=1366&bih=558&cad=b&sei=zYdBUJTXAeWg0QXkyoDYBQ&bav=on.2,or.r_gc.r_pw.r_cp.r_qf.&sei=QdRBUPbBIuHT0QW8vYD4BQ i hope i am clear – user1515425 Sep 01 '12 at 09:30
0

You just want to replace all the numbers with ????

var text = "1-4 Atletico Madrid – Falcao On";
var replaced=text.replace(/\d/g, "???");
​alert(​replaced);​

Use this as a jumping off point, since you'll only want to get the text, not the other html parts.

Charlie
  • 11,380
  • 19
  • 83
  • 138