问题
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