I would like to use a variable in RegExp in this function.
checkSocial(platform, link) {
let reg = new RegExp(/^(?:https?:\/\/)?(www\.facebook\.com\/)(?:\S+)/);
return reg.test(link);
}
Doing this:
let reg = new RegExp(`/^(?:https?:\/\/)?(www\.${platform}\.com\/)(?:\S+)/`);
or this:
let reg = new RegExp('^(?:https?:\/\/)?(www\.' + platform + '\.com\/)(?:\S+)');
didn't work. How can I add a variable?
You don't need the slashes when creating RegExp this way, it will add them automatically.
Also, note you would need extra escaping - I think the last \S token was not escaped properly?
This seems to be a more valid pattern:
let platform = 'facebook';
let reg1 = new RegExp(`^(?:https?:\/\/)?(www\.${platform}\.com\/)(?:\S+)`)
let reg2 = new RegExp(`^(?:https?:\/\/)?(www\.${platform}\.com\/)(?:\\S+)`)
console.log("1", reg1) // Outputs: /^(?:https?:\/\/)?(www.facebook.com\/)(?:S+)/
console.log("2", reg2) // Outputs: /^(?:https?:\/\/)?(www.facebook.com\/)(?:\S+)/