说我有一个字符串var str = "this is the string";
我想将其与此字符串var str2 = "string is the";
进行比较
并且我希望它使用javascript和regex返回真实或匹配的字符串
答案 0 :(得分:1)
根据您的解释,我创建了一个您需要的示例。在此代码示例中,我创建了一个函数,该函数将接受两个字符串,它们将被任何非单词字符分割,然后进行比较,而与字符串中的单词顺序无关。如果字符串相同,则不考虑单词顺序而包含相同的单词,它将返回true。
let string1 = "this is the string";
let string2 = "string is the this";
function findMatch( string1, string2 ) {
//split by any non-word character, anything that is not
//a-z, A-Z, 0-9 ( including the _ character )
let splitPattern = /\W/;
let split1 = string1.split( splitPattern );
let split2 = string2.split( splitPattern );
//traverse string1 array
for ( let i = 0; i < split1.length; i++ ) {
let checkForMatch = false;
//traverse string2 array
for( let j = 0; j < split2.length; j++ ) {
if ( split1[ i ] === split2[ j ] ) {
checkForMatch = true;
break;
}
}//inner for
//if match not found in one itteration, strings do not
//match and false should be returned
if ( !checkForMatch ) {
return false;
}
}//outer for
//else it matches so return true
return true;
}//end findMatch
console.log( findMatch( string1, string2 ) );
希望这对您有所帮助。
编辑:否则,如果只想检查string1中是否存在string2,则可以在for循环中切换两个具有拆分结果的数组。