Began to deal with JavaScript for GreaseMonkey. There was a question: how to search for any expression in the source code of the page?
Then a couple more questions:
1) to memorize into a variable some part around the found one.
2) Is it possible to make it easier? (no text matching search.)

An example of what I mean. Let there is the source code (more precisely, its part):

<table cellspacing=0 cellpadding=0> <tr><td></td><td align=center><font color=silver>вверх</font></td><td><font color=silver>север</font></td></tr> <tr><td align=right><font color=silver>запад</font></td><td align=center valign=middle><img src="../design/dimension-9.gif" width=60 height=55 border=0 hspace=0 vspace=0></td><td><font color=silver>восток</font></td></tr> <tr><td align=right><a href="/example/?c=3&b=ad449bf">юг</a></td><td align=center><font color=silver>вниз</font></td><td></td></tr> </table> 

It is required to store the following in a variable: /example/?c=3&b=ad449bf , facing> south

  • If the code is stable, it is easier to see where the key elements are located and to look for them through selectors. And if the code is not stable, then the regulars will not save. - user207618

1 answer 1

Bota text game write?) This is suitable?

 var url = document.querySelector('table').innerHTML.match(/href="([^"]+)"\>юг/)[1]; 

Or:

 var url = document.body.innerHTML.match(/href="([^"]+)"\>юг/)[1]; 

Remember to check this all on the onload handler or onDOMContentLoaded onload so that the data can load.

  • What is [1] at the end of the line for? - Dmitry
  • The parentheses in the regular expression are given by the Capturing group , match() gives the array, where, starting from the index [1] , the content corresponding to the regular expression in brackets is written. - Aleksander K.
  • And under the index [0] - undefined? And in all subsequent indexes, all other matches on this regular expression? - Dmitry
  • No, under the index 0 is a string suitable for the entire regular expression. If nothing was found then .match() will return null . - Aleksander K.