- Pure javascript (non-regex) version:
- /**
- * Find if string has a word
- * */
- function checkStringHasWord(substr,str){
- console.log("Finding word : "+substr+" from string : "+str);
- str = str.toLowerCase();
- substr = substr.toLowerCase();
- console.log("Str length : "+str.length);
- var idx=str.indexOf(substr);
- if(strcmp(substr,str)==0){console.log("equal");return true;}
- var rightIdx=idx+substr.length;
- //equal
- if(idx>0 && idx+substr.length<str.length){
- //middle
- console.log("middle");
- console.log(str[idx-1]);
- console.log(str[idx+substr.length]);
- return isNonChar(str[idx-1]) && isNonChar(str[idx+substr.length]);
- }
- else if(idx==0){
- //left
- console.log("left");
- //console.log("right idx:"+rightIdx);
- console.log(str[rightIdx]);
- return isNonChar(str[rightIdx]);
- }
- else if(idx+substr.length==str.length){
- //right
- console.log("right");
- console.log(str[idx-1]);
- return isNonChar(str[idx-1]);
- }
- else{
- return false;
- }
- }
- function strcmp(a, b)
- {
- return (a < b ? -1 : (a > b ? 1 : 0));
- }
- function isNonChar(chr){
- var matcher = new RegExp("\\W", "i");
- return matcher.test(chr);
- }
- /**
- * Tests
- * */
- function test(){
- console.log(checkStringHasWord("gre","gre"));//true
- console.log(checkStringHasWord("gre","congres"));//false
- console.log(checkStringHasWord("gre","gresdfg"));//false
- console.log(checkStringHasWord("gre","ojfsdgre"));//false
- console.log(checkStringHasWord("gre","gre:math"));//true
- console.log(checkStringHasWord("gre","gre-math"));//true
- console.log(checkStringHasWord("gre","gre math"));//true
- console.log(checkStringHasWord("gre"," gre "));//true
- console.log(checkStringHasWord("gre","jkggdfgdh"));//false
- console.log(checkStringHasWord("gre","jddfgL:GRE"));//true
- console.log(checkStringHasWord("sat","SSAT 2"));//true
- }
Short Code(Regex version):
Equivalent regex pattern "/btext/b"
Equivalent regex pattern "/btext/b"
No comments:
Post a Comment