Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

match exact string in a sentence

Tags:

javascript

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

like image 887
dazzle Avatar asked Mar 21 '11 14:03

dazzle


2 Answers

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.");
}
like image 69
Thomas Li Avatar answered Sep 29 '22 19:09

Thomas Li


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

like image 43
Brad Christie Avatar answered Sep 29 '22 19:09

Brad Christie