How to exactly match a given string in a sentence.
For example if the sentence is var sentence = "A Google wave is basically a document which captures a communication"
and the given string is var inputString= "Google Wave". I need to check the exact presence of Google Wave in the above sentence & return true or false.
I tried
if(sentence.match(inputString)==null){
alert("No such word combination found.");
return false;
}
This works even if someone enters "Google W". I need a way to find the exact match. Please help
OP wants to return false when do search with Google W
.
I think you should use word boundary for regular expression.
http://www.regular-expressions.info/wordboundaries.html
Sample:
inputString = "\\b" + inputString.replace(" ", "\\b \\b") + "\\b";
if(sentence.toLowerCase().match(inputString.toLowerCase())==null){
alert("No such word combination found.");
}
Using javascript's String.indexOf()
.
var str = "A Google wave is basically a document which captures a communication";
if (str.indexOf("Google Wave") !== -1){
// found it
}
For your case-insensitive comparison, and to make it easier:
// makes any string have the function ".contains([search term[, make it insensitive]])"
// usage:
// var str = "Hello, world!";
// str.contains("hello") // false, it's case sensitive
// str.contains("hello",true) // true, the "True" parameter makes it ignore case
String.prototype.contains = function(needle, insensitive){
insensitive = insensitive || false;
return (!insensitive ?
this.indexOf(needle) !== -1 :
this.toLowerCase().indexOf(needle.toLowerCase()) !== -1
);
}
Oop, wrong doc reference. Was referencing array.indexOf
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With