0

So I have this (example) string: 1234VAR239582358X

And I want to get what's in between VAR and X. I can easily replace it using .replace(/VAR.*X/, "replacement"); But, how would I get the /VAR.*X/as a variable?

lendo
  • 190
  • 2
  • 10
  • Does this answer your question? [Regular Expression to get a string between parentheses in Javascript](https://stackoverflow.com/questions/17779744/regular-expression-to-get-a-string-between-parentheses-in-javascript) – XCS Sep 24 '21 at 14:41
  • More specifically, this answer: https://stackoverflow.com/a/17779833/407650 – XCS Sep 24 '21 at 14:42
  • 1
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match – XCS Sep 24 '21 at 14:43

4 Answers4

3

I think what you are looking for might be

string.match(/VAR(.*)X/)[1] 

The brackets around the .* mark a group. Those groups are returned inside the Array that match creates :)

If you want to only replace what's in between "VAR" and "X" it would be

string.replace(/VAR(.*)X/, "VAR" + "replacement" + "X");

Or more generic:

string.replace(/(VAR).*(X)/, "$1replacement$2");
Simon Born
  • 46
  • 3
0

You can try use the RegExp class, new RegExp(`${VAR}.*X`)

0

You can store it as variable like this,

const pattern = "VAR.*X";
const reg = new RegExp(pattern);

Then use,

.replace(reg, "replacement");
Antajo Paulson
  • 555
  • 1
  • 4
  • 15
0

If you

want to get what's in between VAR and X

then using .* would do the job for the given example string.

But note that is will match until the end of the string, and then backtrack to the first occurrence of X it can match, being the last occurrence of the X char in the string and possible match too much.

If you want to match only the digits, you can match 1+ digits in a capture group using VAR(\d+)X

const regex = /VAR(\d+)X/;
const str = "1234VAR239582358X";
const m = str.match(regex);

if (m) {
  let myVariable = m[1];
  console.log(myVariable);
}

Or you can match until the first occurrence of an X char using a negated character class VAR([^\r\nX]+)X

const regex = /VAR([^\r\nX]+)X/;
const str = "1234VAR239582358X";
const m = str.match(regex);

if (m) {
  let myVariable = m[1];
  console.log(myVariable);
}
The fourth bird
  • 154,723
  • 16
  • 55
  • 70