0

My attempt was :

var re = new RegExp("\w{" + n + "}", "g");

But it didn't seems to work.

P.S. - I have searched several questions of Stackoverflow thinking it must have been asked before But I didn't find one, so I asked my question.

17
  • What is really what you want to do? Commented Jul 26, 2015 at 18:03
  • I want to split the string, into pairs according to the input (n) given by user. Commented Jul 26, 2015 at 18:03
  • But what have you tried so far? Do you have more code? Commented Jul 26, 2015 at 18:04
  • For example String is 'Divyansh' and n is 2 => ['Di','vy','an','sh']; Commented Jul 26, 2015 at 18:05
  • Just this in return statement var arr = str.match(re); where str is the variable having the string. Commented Jul 26, 2015 at 18:06

1 Answer 1

2

The problem is that \ is not only the escape character in regex but also in JS strings. So when you create a regular expression from a string you need to escape it. This means that \w becomes "\\w" in a string and if you want to match a single \ it would even become "\\\\".

Instead of changing it to \\w you can also use . if you don't care about the characters or if the string was validated before.

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

2 Comments

\ is not only the escape character in regex but also in JS strings I didn't knew that earlier, any link where where I can learn about that is much appreciated ^_^
@DivyanshBatham I like this source regular-expressions.info/reference.html, but I usually already know what I'm looking for, should still give a good overview. To test regex online there are many sites, just enter the italic text in a search engine. PS: As Jan said, if you put the things you said in the comments in the question it is more likely to get upvoted.

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.