1

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.

1
  • My current workaround is to cacatenate ^ to the string before passing it to the regex, but there should be a proper way of going about it Commented Jul 9, 2021 at 19:07

2 Answers 2

1

as first I want to say in javascript we can write regex 2 ways

  1. literal likes /pattern/modifiers using slashes /
  2. 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

Sign up to request clarification or add additional context in comments.

Comments

0

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.