Home > Net >  RegExp working on RegExr but not in my JavaScript program
RegExp working on RegExr but not in my JavaScript program

Time:07-01

I'm trying to pull the username (danielj) from this URL:

https://danielj.tr.cwhq-apps.com/i_m113_intro_prog_py_09/ghost-busters

This regular expression seems to be what I need if I want to get the username in the first capturing group:

https:\/\/(\w )\.

I tried it on RegExr https://regexr.com/6osbp and it gives me exactly what I want (the first capturing group contains danielj).

When I run the same logic in a JavaScript program, I get null:

function getUsername(url) {
    const re = new RegExp("https:\/\/(\w )\.");
    const match = url.match(re);
    return match
}

const url = "https://danielj.tr.cwhq-apps.com/i_m113_intro_prog_py_09/ghost-busters";

const match = getUsername(url);

console.log(match); // null

My JavaScript is a bit rusty, but I thought this seemed straightforward enough. What am I missing?

I've read through these docs to refresh my JS memory, and it seems like everything matches up syntax-wise:

CodePudding user response:

You forgot to escape the \ for \w. Because the RegExp constructor requires a string, you need to be mindful of escaping backslashes.

const re = new RegExp("https:\/\/(\\w )\.");
const match = url.match(re);

CodePudding user response:

It seems to work with the literal expression.

function getUsername(url) {
    const re = /https:\/\/(\w )\./;
    const match = url.match(re);
    console.log(match);
}

const url = "https://danielj.tr.cwhq-apps.com/i_m113_intro_prog_py_09/ghost-busters";

getUsername(url);
  • Related