Reputation: 4294
I'm having a little problem, when I want to check if a word from one input, exist in another input.
The first input can only contain one word. When I've typed a word and then hit space, the script should check if the word already exist in the second input.
It works fine, except when I'm using a +
-sign.
If c++
exist in the second input, and I'm typing c
in the first input, and then hit space, it tells that the word already exist, which is incorrect.
I've tried to search to web for a solution, and what I've found was something with regEx
and escaping
, but it still doesn't seems to work.
This is what I've tried so far:
$word = $('input.word').val();
$check_here = $('input.check-here').val();
function escapeRegExp(string) {
$regex = '\\b';
$regex += string.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
$regex += '\\b';
$result = new RegExp($regex, "g");
return $result;
}
if ( escapeRegExp( $word ).test( $check_here ) ) {
alert("Word exist");
}
else {
alert("Word do not exist");
}
PS: I've also tried to put $check_here
in the escapeRegExp()
function, like I've done with $word
, but that do not work at all.
A friendly person, who please can tell me whats wrong?
Upvotes: 1
Views: 253
Reputation: 3919
I do not understand why you want to escape the string.
Your escapeRegExp function (which does not escapes anymore so now called regExp) should be simple like this:
function regExp(string) {
//this regex will match only if there is the same string in your list.
//Only spaces are used as boundaries.
return new RegExp("\s"+string+"\s", "g");
}
As an alternative, you can put all the words in the second input in an array, like in my fiddle:
var existingWords = $('input#wordList').val().split(/ /);
if( existingWords.indexOf( word ) >= 0 )
http://jsfiddle.net/gael/a2tr9tud/1/
Upvotes: 2