0

I am using the following XPath instruction in a JS function that highlights certain keywords on web pages:

var xpath = "//text()[contains(., \"" + keyword + "\")]";

Any idea on how I could rewrite it in order to support regex? I tried in various ways, but nothing seemed to work!

kjhughes
  • 106,133
  • 27
  • 181
  • 240
Alex
  • 85
  • 7

1 Answers1

0

You can rewrite

var xpath = "//text()[contains(., \"" + keyword + "\")]";

using regex as

var xpath = "//text()[matches(., \"" + keyword + "\")]";

and then keyword could be a regex rather than only a string.

However, regex functions such as matches() require XPath 2.0+. Native XPath libraries in browsers only support XPath 1.0.

See also

kjhughes
  • 106,133
  • 27
  • 181
  • 240
  • I already tried using 'matches' instead of 'contains', but it does not work! However, your answer was very useful to me, because it's now clear why this is not working... XPath libraries in browsers only support XPath 1.0! Thank you for your answer, and the links you provided. Very helpful! – Alex Jul 31 '20 at 12:47
  • Kenneth, do you think xpath.js (https://github.com/ilinsky/xpath.js) would be helpful in my case? If so, how should the XPath query look like, based on the code I already provided above? There is also jquery-xpath.js (https://github.com/ilinsky/jquery-xpath). I'd like to mention that I run my highlighting script using Tampermonkey. – Alex Jul 31 '20 at 14:01
  • Sorry, there are too many undefined requirements for me to advise you based on your comment, and this is not the right forum for design advice. I won't extend this dialog further but will leave you with this thought: If you're only searching text as your current XPath suggests, and regex is important to you, consider abandoning XPath and using the browser's built-in support for regex directly. Good luck. – kjhughes Jul 31 '20 at 14:18
  • Sure, I completely understand. Thank you very much! – Alex Jul 31 '20 at 15:09