javascript - Validate Regex with minimum length and new line - Stack Overflow

I am trying to match string having length > 10var value = "Lorem Ipsum is simply dummy text of

I am trying to match string having length > 10

var value = "Lorem Ipsum is simply dummy text of the printing and type";
/^.{10,}$/.test(value);

returns true;

But, if I have a string with new line character then it fails.

How can i update regular expression to fix that.

I know I can just check .length > 10 or replace new line with space in value. But, i want to update regular expression.

I am trying to match string having length > 10

var value = "Lorem Ipsum is simply dummy text of the printing and type";
/^.{10,}$/.test(value);

returns true;

But, if I have a string with new line character then it fails.

How can i update regular expression to fix that.

I know I can just check .length > 10 or replace new line with space in value. But, i want to update regular expression.

Share Improve this question asked Jun 23, 2014 at 11:32 YogeshYogesh 3,4829 gold badges32 silver badges46 bronze badges 2
  • Why are you insistent on REGEX for this? You've said yourself that there's an easier way – Mitya Commented Jun 23, 2014 at 11:36
  • @Utkanos Same Regular expression in used to validate on server, Where I do not have control. So, I do not want to just fix it in JavaScript by easier way. – Yogesh Commented Jun 23, 2014 at 11:40
Add a ment  | 

3 Answers 3

Reset to default 4

JavaScript does not have a native option for dot matches newlines. To get around this, use a different selector:

[\S\s]

This will match any Whitespace or Non-Whitespace character.

var s = "some\ntext\n",
    r = /^[\S\s]{10,}$/;
console.log(r.test(s));

And, the obligatory fiddle: http://jsfiddle/kND83/

There are libraries, such as http://xregexp./, that add options for dot matches newlines, but all they do is sub in [\S\s] for the . in your Regex.

If it's just length you're testing you should just use .length. If you insist in regex, the dot actually matching everything except a newline. You can change this by searching for \s\S instead:

([\s\S]{10,})

this matches any whitespace and any non whitespace, covering the entire spectrum. Sadly, the s modifier is not supported by js regex.

^ and $ mandate the start and end of a line in the match. Just remove them, and you'll have your answer. Oh, and you need the m switch to pass newlines.

var r = /.{10,}/m;
r.test(value);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744962636a4603481.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信