5

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

Anas
  • 5,622
  • 5
  • 39
  • 71
Job Sturm
  • 95
  • 2
  • 8

2 Answers2

4

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 strings = [
  "There is this one thing that I'm trying to do but I have no idea how",
  "I really have no clue how too fix it",
  "Hopefully maybe someone can help me"
]

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

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

vsync
  • 118,978
  • 58
  • 307
  • 400
Jonny 5
  • 12,171
  • 2
  • 25
  • 42
  • Thanks for that, there is only one problem now, how do I get my user input inside that regex? – Job Sturm Mar 23 '14 at 17:15
  • @JobSturm See the updated answer and [fiddle](http://jsfiddle.net/82pZ7/2/), if that's what you mean. Building the regex from str, where white-spaces are replaced with `\b.*\b` (boundary, joker, boundary) – Jonny 5 Mar 23 '14 at 18:35
  • Similar, I liked this because the word could be in any order. http://stackoverflow.com/a/13911776/1223763 – eephillip Jan 18 '15 at 18:31
-1
<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

Ferrakkem Bhuiyan
  • 2,741
  • 2
  • 22
  • 38