Home >Web Front-end >JS Tutorial >Matching of two strings in JavaScript
I encountered a problem at work. Two strings are matched. The requirement is: each string contains at most one *, ? can be unlimited
* represents a string of any length, and ? represents one character
The request can prompt two conflicts
< ;input type="button" onclick="checkMarchX()" value="CHECK">
Use Javascript to implement the code as follows:
[javascript]
function checkMarchX()
Of(' *');
var str2XPosition = str2.indexOf('*');
var position = str1XPosition>str 2XPosition?str2XPosition ; (0,position);
))
var str1XBackPosition = str1.length-str1XPosition-1;
var str2XBackPosition = str2. length-str2XPosition-1;
var backposition = str1XBackPosition>str2XBackPosition?str2XBackPosition:str1XBackPosition; PatbackStr1 = str1.substring (Str1.length-Backposition, Str1.length);
VAR PATBACKSTR2 = Str2.Substring (str2.length-backposition, str2.length); C If (CheckMarchq (PatBackstr1, PatBackstr2))
{
Alert (str1+' and '+str2+"conflict");
//alert(str1+'与'+str2+"前半部分冲突");
var str1XBackPosition = str1.length-str1XPosition-1;
var str2XBackPosition = str2.length-str2XPosition-1;
var backposition = str1XBackPosition>str2XBackPosition?str2XBackPosition:str1XBackPosition;
if (backposition==0)
{
alert(str1+'与'+str2+"冲突");
}
else
{
var patbackStr1 = str1.substring(str1.length-backposition,str1.length);
var patbackStr2 = str2.substring(str2.length-backposition,str2.length);
if(checkMarchQ(patbackStr1,patbackStr2))
{
alert(str1+'与'+str2+"冲突");
}
}
}
}
else if((str1XPosition==-1 && str2XPosition!=-1)||(str1XPosition!=-1 && str2XPosition==-1))//有且只有一个字符串含有*
{
var strX = str1XPosition==-1?str2:str1;//含有*的字符串
var strNoX = str1XPosition==-1?str1:str2;//不含*的字符串
if (strX.length-1
var position = strX.indexOf('*');
if(position==0)
{
//alert(str1+'与'+str2+"前半部分冲突");
var backposition = strX.length-position-1;
if (backposition==0)
{
alert(str1+'与'+str2+"冲突");
}
else
{
var patbackStr1 = str1.substring(str1.length-backposition,str1.length);
var patbackStr2 = str2.substring(str2.length-backposition,str2.length);
if(checkMarchQ(patbackStr1,patbackStr2))
{
alert(str1+'与'+str2+"冲突");
}
}
}
else
{
var patbeforeStr1 = str1.substring(0,position);
var patbeforeStr2 = str2.substring(0,position);
if(checkMarchQ(patbeforeStr1,patbeforeStr2))
{
//alert(str1+'与'+str2+"前半部分冲突");
var backposition = strX.length-position-1;
if (backposition==0)
{
alert(str1+'与'+str2+"冲突");
}
else
{
var patbackStr1 = str1.substring(str1.length-backposition,str1.length);
var patbackStr2 = str2.substring(str2.length-backposition,str2.length);
if(checkMarchQ(patbackStr1,patbackStr2))
{
alert(str1+'与'+str2+"冲突");
}
}
if(checkMarchQ(str1,str2))
(str1 , str2)
{
var flagque = false;
if (str1.length == str2.length) {
// The same length can be conflicted
for (var I = 0; str1.Length; i ++)
str(i,1)!=str2. substr(i,1))
} }
The * is at least one character. The above program does not verify the legality of the input