0

I wrote a TamperMonkey script to clean up LinkedIn results so jobs won't show if they don't meet certain criteria such as pay range. To do this I have the following:

var payYr = $(jobItem).text().toLowerCase().trim().match(/\$(.+?k?)\/yr/g);
console.log(payYr);

I've tested the regex repeatedly on live test sites which confirm that the resulting set should be an array of ONLY the numbers between the $ and the '/yr' values. That will usually be $##/yr or $###/yr values.

Input would be strings such as:

$115K/yr - $145K/yr · 6 benefits $180K/yr - $210K/yr

Expected output:

Array [ "115k", "145k" ];
Array [ "180k", "210k" ];

Instead, in Firefox, when I test it I'm getting arrays like so:

Array [ "$115k/yr", "$145k/yr" ];
Array [ "$180k/yr", "$210k/yr" ]

I can't figure out why the dollar sign and /yr values are being returned. By all accounts, that shouldn't happen and I don't know what's going on or how to fix it.

not_a_generic_user
  • 1,906
  • 2
  • 19
  • 34
  • Please post a [mre] with an example of the text you're trying to extract from. – Barmar Jun 29 '23 at 17:36
  • You have several `console.log()` calls in your code snippet. Which of them is that example output from? – Barmar Jun 29 '23 at 17:37
  • I've uploaded the whole script. The output is from the console.log(payYr); in the Yearly pay section. – not_a_generic_user Jun 29 '23 at 17:38
  • The "whole script" is not a MINIMAL example. We just need to see the text and the regexp extraction. – Barmar Jun 29 '23 at 17:38
  • Get rid of the `g` flag. That's returning an array of matches of the entire regexp, not the capture groups. – Barmar Jun 29 '23 at 17:41
  • Updated to the minimum code, input, expected output, and actual output. Removing the /g flag produces unwanted output in terms of matching only the first result and no others. – not_a_generic_user Jun 29 '23 at 17:44
  • Without the `g` flag it will return the first match, with each array element corresponding to a capture group. – Barmar Jun 29 '23 at 17:44
  • I need the last match in the string. That requires either regex that can retrieve only the last match or that returns all matches so I can pop it off the array to achieve the same result. – not_a_generic_user Jun 29 '23 at 17:45
  • 1
    See [docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match#return_value) on `String.prototype.match()`. Namely: "_Return value:_ If the `g` flag is used, all results matching the complete regular expression will be returned, but capturing groups are not included. If the `g` flag is not used, only the first complete match and its related capturing groups are returned." – romellem Jun 29 '23 at 17:46
  • Thanks for the "capture group" terminology - that will help. Also thanks for clarifying that javascript can't do what I'm wanting. It's suprising, but so be it. I'll adjust the code to remove the superfluous characters. – not_a_generic_user Jun 29 '23 at 17:52

0 Answers0