Skip to main content
dublove
Legend
June 4, 2026
Answered

How to use a regular expression on a variable to find a target?

  • June 4, 2026
  • 1 reply
  • 31 views

For example, I want to find numbers in the `source` variable.
The output is null?
What's wrong?
 

var source="@m2Title";

//Default regular expression
var re="(?<=@m)(\\d+)(?!\\d)"

//Standard Regular Expressions
var toReg=new RegExp(re);

var result=source.match(toReg);
alert(result);

 

    Correct answer Peter Kahrel

    Your second line defines just a string, not a regular expression. The third line isn’t necessary. The lookahead isn’t needed either in this case: \d+ continues until it runs into something that’s not a digit.

    Also, JavaScript’s regular-expression engine doesn’t have lookbehind, so you’d do something like this:

    var source="@m2Title";
    //Default regular expression
    var re=/@m(\d+)/;
    var result=source.match(re);
    alert(result);

    Remember that ‘result’ is an array here.

    1 reply

    Peter Kahrel
    Community Expert
    Peter KahrelCommunity ExpertCorrect answer
    Community Expert
    June 4, 2026

    Your second line defines just a string, not a regular expression. The third line isn’t necessary. The lookahead isn’t needed either in this case: \d+ continues until it runs into something that’s not a digit.

    Also, JavaScript’s regular-expression engine doesn’t have lookbehind, so you’d do something like this:

    var source="@m2Title";
    //Default regular expression
    var re=/@m(\d+)/;
    var result=source.match(re);
    alert(result);

    Remember that ‘result’ is an array here.

    dublove
    dubloveAuthor
    Legend
    June 4, 2026

    Hi ​@Peter Kahrel 

    I only want numbers \d+

    Thank you very much.

    I found it:

    var result=source.match(re)[1];

     

    Peter Kahrel
    Community Expert
    Community Expert
    June 4, 2026

    This is very basic JavaScript regular-expression stuff. As it is, the regular expression returns null if there's no match, or a two-element array. The first element is the whole match (@m2), the second element is what was captured in the parentheses (2).

    Change the alert as follows:

    if (result == null) {
    alert('No result');
    } else {
    alert (result[1]);
    }