0

Okay so the title must be a head scratcher, but here is the full string:

y = "_target"
x = "_"

string A = "prefix_param_name_id_set_selected_param_name_index__target_"
string B = "prefix_param_name_id_set_selected_param_name_index_target_"
  1. regex looks for "y"
  2. "y" will always be the value between the last occurrence of "x"
  3. if the last occurrence of "x" is preceded with double "x" then regex assumes the second part of double "x" is part of "y"

so returning "y" where at one instance "y" may be "_target" and at another "y" may be "target"

This is where I am at:

var str = "prefix_param_name_id_set_selected_param_name_index__target_";
alert(str.match(/\(([^)]*)\)[^(]*$/)[1]);

returns "target"; it should be "_target".

UPDATE:

Please note that "y" is a variable and is unknown. str is known, but the regex does not know what "y" is, only that it is found between at the last occurrence of "x"

Jacques Joubert
  • 111
  • 1
  • 10
  • 1
    When I run `var str = "prefix_param_name_id_set_selected_param_name_index__target_"; alert(str.match(/\(([^)]*)\)[^(]*$/)[1]);` I get null – chinloyal Mar 14 '18 at 12:42

1 Answers1

0

You need to use x and y to create the regular expression

var y = "_target";
var x = "_";
var regexp = new RegExp("(?<=" + x + ")(" + y + ")(?=" + x + ")", "g");
var input = "prefix_param_name_id_set_selected_param_name_index__target_";
var matches = input.match(regexp);

matches outputs

["_target"]

Explanation

  • Use (?<=" + x + ") to check if y follows x
  • (" + y + ") captures y
  • (?=_) checks if x follows y as well.

Demo

var y = "_target";
var x = "_";
var regexp = new RegExp("(?<=" + x + ")(" + y + ")(?=" + x + ")", "g");
var input = "prefix_param_name_id_set_selected_param_name_index__target_";
var matches = input.match(regexp);
console.log(matches);
gurvinder372
  • 66,980
  • 10
  • 72
  • 94