Match exact string in sentence

How to exactly match a given string in a sentence.

For example, if the sentence var sentence = "Google wave is basically a document that captures the message"

and this line is var inputString = "Google Wave". I need to check the exact presence of Google Wave in the above sentence and return true or false.

I tried

if(sentence.match(inputString)==null){ alert("No such word combination found."); return false; } 

This works even if someone is on Google W. I need a way to find an exact match. Please, help

+4
source share
3 answers

OP wants to return false when searching with Google W

I think you should use the word boundary for regular expression.

http://www.regular-expressions.info/wordboundaries.html

Example:

 inputString = "\\b" + inputString.replace(" ", "\\b \\b") + "\\b"; if(sentence.toLowerCase().match(inputString.toLowerCase())==null){ alert("No such word combination found."); } 
+4
source

Using javascript 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 comparison, case insensitive and easy:

 // makes any string have the function ".contains([search term[, make it insensitive]])" // usage: // var str = "Hello, world!"; // str.contains("hello") // false, it 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, invalid document link. Link to array.indexOf

+4
source

ContainsExactString2 was only to me more in-depth than necessary, '===' should work just fine

 <input id="execute" type="button" value="Execute" /> // Contains Exact String $(function() { var s = "HeyBro how are you doing today"; var a = "Hey"; var b = "HeyBro"; $('#execute').bind('click', function(undefined) { ContainsExactString(s, a); ContainsExactString(s, b); }); }); function ContainsExactString2(sentence, compare) { var words = sentence.split(" "); for (var i = 0; i < words.length; ++i) { var word = words[i]; var pos = 0; for (var j = 0; j < word.length; ++j) { if (word[j] !== compare[pos]) { console.log("breaking"); break; } if ((j + 1) >= word.length) { alert("Word was found!!!"); return; }++pos; } } alert("Word was not found"); } function ContainsExactString(sentence, compare) { var words = sentence.split(" "); for (var i = 0; i < words.length; ++i) { if(words[i] === compare) { alert("found " + compare); break; } } alert("Could not find the word"); break; } 
0
source

Source: https://habr.com/ru/post/1344614/


All Articles