How to check if a string contains multiple words on different locations

自闭症网瘾萝莉.ら 提交于 2020-01-25 03:39:25

问题


So I have multiple string that are like this:

String 1: There is this one thing that I'm trying to do but I have no idea how.
String 2: I really have no clue how too fix it.
String 2: Hopefully maybe someone can help me.

Now I also have a string that is a search input that can be anything, for example:

There idea

When the user inputs and sends that I want the JavaScript too match with string 1.
Also I would like too have it return by how many characters the two strings are matching.

If someone can help me with this I would be very grateful.

Thanks in advance,

Job


回答1:


If you want to know the length of the match, e.g. using regex:

var str = "There idea";

var pattern = new RegExp("\\b" + str.replace(/ +/g, "\\b.*\\b") + "\\b", "i");
console.log(pattern);

var input = new Array(
  "String 1: There is this one thing that I'm trying to do but I have no idea how.",
  "String 2: I really have no clue how too fix it. ",
  "String 3: Hopefully maybe someone can help me. "
);

for(i=0; i<input.length; i++) {
  if(res=input[i].match(pattern)) {
    console.log(res[0], res[0].length);
  }
}

\b matches a word boundary (zero-length match)




回答2:


<script>
        $(document).ready(function () {
            var myTestValue = ['test1', 'test2', 'test3'];

            for (var i = 0; i < myTestValue.length; i++) {
                if(window.location.href.indexOf(myTestValue[i]) > -1) {
                    alert("your contains the string "+myTestValue[i]);
                }
            }
        });
</script>

i don't know it's help you or not ..But i wish you get Idea from that @Job Sturm



来源:https://stackoverflow.com/questions/22593470/how-to-check-if-a-string-contains-multiple-words-on-different-locations

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