-3

I'm trying to extract the string between two different parts of a string, but I have encountered a problem. This is the string I'm wokring with:

onclick="functionName(1816, 1718, 0);"

The part of the string that I'm trying to extract is "1718", ie the second parameter of the function. I have tried doing this like so:

$(this).attr('onclick').substring($(this).attr('onclick').lastIndexOf(", ") + 1, $(this).attr('onclick').lastIndexOf(", "));

This gets the onclick value and should extract what's between ", " and ", " but it's not doing so, it outputs ",".

Thanks for any input on this!

javgogel
  • 69
  • 2
  • 5
  • This question is found in lots of different forms across Stack Overflow. [This search](/search?q=%5Bjs%5D+get+string+between+delimiters) finds several of them. More about searching [here](/help/searching). But with that said: JavaScript code cannot be correctly parsed with naive approaches like `indexOf` or a single regular expression. If you need to parse JavaScript code, use a JavaScript parser. There are several free ones, such as [Esprima](http://esprima.org/). – T.J. Crowder Apr 11 '20 at 13:08

2 Answers2

0

if you know it's always the middle "parameter" this will work for you:

let onclick = "functionName(1816, 1718, 0);"
console.log(onclick.split(',')[1].trim());
Omri Attiya
  • 3,917
  • 3
  • 19
  • 35
0

You could match the wanted part between commas.

var string = 'onclick="functionName(1816, 1718, 0);"',
    part = string.match(/,\s*([^,]+),/)?.[1];

console.log(part);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392