最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to match strings with and without space using regular expression? - Stack Overflow

programmeradmin1浏览0评论

I have a regular expression, which matches exact words, if space is in between, it returns false. How can i achieve this? even though I have a space in between or not it has to return true. EX:

var str1 = "This is a fruit";
var str2 = "this is afruit";

str2 = str2.toLowerCase();

if(str2.toLowerCase().match(/a fruit/)){
  alert("matched");
  return true;
} 
return false;

In the above if condition, I have mentioned .match(/a fruit/) it wil return me false because i'm considering space too. I dont want to do like this. Enven if it is "a fruit" or "afruit" it has to return me true. I'm new to regular expression Please help.. I'm stuck here.

I have a regular expression, which matches exact words, if space is in between, it returns false. How can i achieve this? even though I have a space in between or not it has to return true. EX:

var str1 = "This is a fruit";
var str2 = "this is afruit";

str2 = str2.toLowerCase();

if(str2.toLowerCase().match(/a fruit/)){
  alert("matched");
  return true;
} 
return false;

In the above if condition, I have mentioned .match(/a fruit/) it wil return me false because i'm considering space too. I dont want to do like this. Enven if it is "a fruit" or "afruit" it has to return me true. I'm new to regular expression Please help.. I'm stuck here.

Share Improve this question edited Nov 23, 2012 at 14:54 Alan Moore 75.3k13 gold badges107 silver badges161 bronze badges asked Nov 21, 2012 at 5:41 madhumadhu 1,0187 gold badges21 silver badges39 bronze badges 2
  • do you want to match any sequence of letters or only "afruit"? – hd1 Commented Nov 21, 2012 at 5:48
  • You are using toLowerCase() twice for str2 - not really necessary... Also - you can use /regex/i to match case-insensitive. – Dror Commented Nov 21, 2012 at 5:55
Add a ment  | 

4 Answers 4

Reset to default 7
/a ?fruit/

or, prettier,

/a\s?fruit/

? means that the previous character is optional. \s is any kind of whitespace.

According to Javascript regular expressions reference:

str2 = str2.toLowerCase();
does_it_match = str2.match(/[a-z ]+/);
if (does_it_match) { return true; }
return false;
var str1 = "This is a fruit";
var str2 = "this is afruit";


str1 = str1.replace(/\s/g, '');
str2 = str2.replace(/\s/g, '');

This will remove white spaces from string. then convert both into lower case and pare as you are.

Use Below Example

var str1 = "This is a fruit";
var str2 = "this is afruit";

str2 = str2.toLowerCase();
var matchString = 'a fruit';
matchString = matchString.replace(/\s+/g,'');
if(str2.toLowerCase().match(matchString)){
  alert("matched");
  return true;
} 
return false;
发布评论

评论列表(0)

  1. 暂无评论