1

The following word can be an entry:

1200
90
Ashton
Created By
Johnson & Johnson
Lemon Pie
Xavier

I have the following RegEx:

var rexp = new RegExp('^' + val, 'i');

I am entering the following:

If I enter `12`, there is a match, `1200`.

If I enter `Lem`, there is a match, `Lemon Pie`.

If I enter `Lemon P`, there is no match.

If I enter `Johnson &`, there is no match.

If I enter `&`, there is no match.

How can I modify the RegExp() function, so it takes space into account to find a match, so:

If I enter `12`, there is a match, `1200`.

If I enter `Lem`, there is a match, `Lemon Pie`.

If I enter `Lemon P`, there is a match, `Lemon Pie`.

If I enter `Johnson &`, there is a match, `Johnson & Johnson`.

If I enter `&`, there is a match, `Johnson & Johnson`.
0

1 Answer 1

2

You can replace all space with \\s.

E.g.

var pattern = '^' + val.replace(' ', '\\s');
var rexp = new RegExp(pattern, 'i');

\\s will print as \s, which matches space in your word.

If you also want to replace multiple spaces with one space in your pattern, you can also do it like,

var pattern = '^' + val.replace(/\s+/, '\\s');

Here's your Fiddle

Edit:

^ matches for the beginning of line. If you just want to matches the word that you enter in the input, without matching the starting letter, then you can avoid regex in the first place.

Check this Fiddle

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

14 Comments

Might be worth mentioning how error prune it will be to use user data to generate a regex, eg if val='?' the regex will fail: /^?/i
@Si8 you're not matching the regex against the data, but against $('span', this).text().split(" ").join("") which remove spaces from it. The regex has no problem, the data you match it against has. Try using lemonp as input, it will match 'Lemon Pie'.
@Si8 Please check the updated Fiddle.
@Si8 Because your original regex uses ^ which matches the beginning of line. You don't have any word starts with '&', do you? If you just want to match for any word, it'd be much simpler if you don't use regex at all.
I like the non regex solution. I accepted and +1 your answer. Thank you.
|

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.