madhu
madhu

Reputation: 1018

How to match strings with and without space using regular expression?

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.

Upvotes: 3

Views: 7530

Answers (4)

Suman Singh
Suman Singh

Reputation: 1377

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;

Upvotes: 0

Dev
Dev

Reputation: 6720

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 compare as you are.

Upvotes: 0

hd1
hd1

Reputation: 34677

According to Javascript regular expressions reference:

str2 = str2.toLowerCase();
does_it_match = str2.match(/[a-z ]+/);
if (does_it_match) { return true; }
return false;

Upvotes: 0

Amadan
Amadan

Reputation: 198556

/a ?fruit/

or, prettier,

/a\s?fruit/

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

Upvotes: 7

Related Questions