Check if a string has a word in javascript (and not just substring) : non-regex version

    Pure javascript (non-regex) version:
  1. /**
  2. * Find if string has a word
  3. * */
  4. function checkStringHasWord(substr,str){
  5. console.log("Finding word : "+substr+" from string : "+str);
  6. str = str.toLowerCase();
  7. substr = substr.toLowerCase();
  8. console.log("Str length : "+str.length);
  9. var idx=str.indexOf(substr);
  10. if(strcmp(substr,str)==0){console.log("equal");return true;}
  11. var rightIdx=idx+substr.length;
  12. //equal
  13. if(idx>0 && idx+substr.length<str.length){
  14. //middle
  15. console.log("middle");
  16. console.log(str[idx-1]);
  17. console.log(str[idx+substr.length]);
  18. return isNonChar(str[idx-1]) && isNonChar(str[idx+substr.length]);
  19. }
  20. else if(idx==0){
  21. //left
  22. console.log("left");
  23. //console.log("right idx:"+rightIdx);
  24. console.log(str[rightIdx]);
  25. return isNonChar(str[rightIdx]);
  26. }
  27. else if(idx+substr.length==str.length){
  28. //right
  29. console.log("right");
  30. console.log(str[idx-1]);
  31. return isNonChar(str[idx-1]);
  32. }
  33. else{
  34. return false;
  35. }
  36. }
  37. function strcmp(a, b)
  38. {
  39. return (a < b ? -1 : (a > b ? 1 : 0));
  40. }
  41. function isNonChar(chr){
  42. var matcher = new RegExp("\\W", "i");
  43. return matcher.test(chr);
  44. }
  45. /**
  46. * Tests
  47. * */
  48. function test(){
  49. console.log(checkStringHasWord("gre","gre"));//true
  50. console.log(checkStringHasWord("gre","congres"));//false
  51. console.log(checkStringHasWord("gre","gresdfg"));//false
  52. console.log(checkStringHasWord("gre","ojfsdgre"));//false
  53. console.log(checkStringHasWord("gre","gre:math"));//true
  54. console.log(checkStringHasWord("gre","gre-math"));//true
  55. console.log(checkStringHasWord("gre","gre math"));//true
  56. console.log(checkStringHasWord("gre"," gre "));//true
  57. console.log(checkStringHasWord("gre","jkggdfgdh"));//false
  58. console.log(checkStringHasWord("gre","jddfgL:GRE"));//true
  59. console.log(checkStringHasWord("sat","SSAT 2"));//true
  60. }

Short Code(Regex version):
Equivalent regex pattern "/btext/b"

No comments:

Post a Comment