Please what is the RegExp equivalent of /^STRINGA/i in javascript?
For example, new RegExp('country', 'i') will give /country/i, but i do not know how to achieve the aforementioned regex.
2 Answers
as first I want to say in javascript we can write regex 2 ways
- literal likes /pattern/modifiers using slashes /
- constructor likes new RegExp("pattern", "modifiers") using constructor function
regex has several special characters if a pattern has a special character you can scaping with the use of backslash \ this backslash also I used inside of StackOverflow editor 2-time then it showed it scaping any special character.
const pattern = /\/\^STRINGA\/i/;
const string = '/^STRINGA/i';
console.log(string.match(pattern));
Note: / / first and last slashes used to making the regex pattern, and all \ backslash used for scaping the special character
Comments
You just need to escape special characters. For example, using the RegExp constructor, you can do this:
const ex = new RegExp('\\/\\^STRINGA\\/i');
console.log('/^STRINGA/i'.match(ex));
And using an expression, you can do this:
const ex = /\/\^STRINGA\/i/;
console.log('/^STRINGA/i'.match(ex));
^to the string before passing it to the regex, but there should be a proper way of going about it