3

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.

2
  • do you want to match any sequence of letters or only "afruit"? 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. Commented Nov 21, 2012 at 5:55

4 Answers 4

7
/a ?fruit/

or, prettier,

/a\s?fruit/

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

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

Comments

0

According to Javascript regular expressions reference:

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

Comments

0
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.

Comments

0

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;

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.