The equality of LIKE '%$word%' in JavaScript RegExp AKA How to make a JavaScript search engine

ぃ、小莉子 提交于 2019-12-24 02:25:11

问题


I have a localStorage object that contains JSON data that yes, I have already parsed.

Within that data, I wish to search an array for something, such as "ANYTHING HERE "+keyword+"ANYTHING HERE"; Like an SQL "LIKE ''" query.


Ahh yes, indexOf seems to work fine for it. All I have to do now is just make a simple RegExp to validate the search input (only for length and characters--nothing fancy.)

You see, I am working on a local application that Google Chrome users will be able to set as their homepage, and hopefully, I can come up with some cool never-before-seen features.


回答1:


If you want to know if one string appears within another you might want to use the indexOf method.

if(jsonstring.indexOf(keyword) != -1){
    console.log("keyword appears in jsonstring");
}



回答2:


May be this if you are using javascript

pattern = /keyword/g
for(i=0;i<jsonobj.length;i++){
    if(pattern.test(jsonobj[i])){
        // it matches the element that has the text 'keyword' in it
    }
}



回答3:


Try this regex pattern /\w*X\w*/gi

Example: Find any like OR, AND to replace uppercase.

g: Global i: insensitive m: multi-line

let _like = "examPle OrTeeeeest tOst iAnDi liKe oRNot MK7".replace(/\w*AND\w*|\w*OR\w*/gi, 
  function (x) {
    return x.toUpperCase();
  });
console.log(_like);


来源:https://stackoverflow.com/questions/9464457/the-equality-of-like-word-in-javascript-regexp-aka-how-to-make-a-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!