How to check if a String completes another?

4

I would like to know if there is any function or operator that can check if a String looks like another in javascript for example:

var str1 = "joao foi ao mercado";
var str2 = "joao fo";

What I need is to compare the first with the second one, if the second one is a piece of the first then it returns true (like the type of mysql)

    
asked by anonymous 14.08.2017 / 20:55

4 answers

3
var str1 = "joao foi ao mercado";
var str2 = "joao fo";

if ( str1.contains(str2)  ) 
    //é parrte
else
    //não é parte

Here are several other ways link

    
14.08.2017 / 21:28
3

One option is to use the String.prototype.search() method. . If the return is -1 does not exist, otherwise it is because it exists. See:

var str1 = "O menino joao foi ao mercado";
var str2 = "joao fo";

function compare(str1, str2){
    return (str1.search(str2)>0)? true : false;
}

console.log(compare(str1,str2)); //true

If you prefer too, another option would be to use regular expression. For this case, it will return false or true , so that string 2 can be anywhere in string 1 . See:

var str1 = "O menino joao foi ao mercado";
var str2 = "joao fo";

var rx = new RegExp(str2);

console.log(rx.test(str1)); //true

You also have String.prototype.includes() :

var str1 = "O menino joao foi ao mercado";
var str2 = "joao fo";


console.log(str1.includes(str2));  // true
console.log(str1.includes("joac"));  // false
    
14.08.2017 / 21:37
1

Would it be an option to use indexof and do your own function?

function ContemString(str1, str2){
    return str1.indexOf(str2) > -1;
}
    
14.08.2017 / 21:18
1

The search () Finds the first substring match in a regular expression search.

var str = "joao foi ao mercado",
substring = /joao fo/;

var pos = str.search(substring);
console.log(pos);

var str = "joao foi ao mercado",
substring = /joao não fo/;

var pos = str.search(substring);
console.log(pos);

var str = "joao foi ao mercado",
substring = /fo/;

var pos = str.search(substring);
console.log(pos);
    
14.08.2017 / 21:25