Home > Back-end >  Convert $x()'s return value to individual strings in browser console (one liner)?
Convert $x()'s return value to individual strings in browser console (one liner)?

Time:07-31

How can I convert the return value of an XPath search $x(), when executed in a browser console, to individual strings so that I can perform string manipulations on the result in a "one-liner"?

Imagine that I run a $x() and the result is three values:

abc
def
ghi

I then want to extract the first letter from each of these result, using something like 'abc'.match("."). It has to be a "one-liner" because the purpose is to distribute it to non-technical users that should be able to just copy-paste it into the console.

Error handling is not necessary.

CodePudding user response:

This Google Chrome console one-liner,

$x('//span').map(e => e.textContent.charAt(0))

will return an array of the first characters of the text content of every span element of the current page. Update the XPath side (//span) or the JavaScript side (.map(e => e.textContent.charAt(0)))) as needed for your particular case.

  • Related