简体   繁体   中英

Determining if one of the two strings is a substring of the other String Javascript?

Suppose I have two text fields where the user can enter any text.

One field can have: The sky is blue.
Second field have: The ocean is blue.

In Javascript what is the easiest way to check if one string entered in one field is a substring for the other field?

So far this is what I have:

<!DOCTYPE html>
<html>
   <head>
      <meta charset="UTF-8">
      <title>Substring Test</title>
      <script type="text/javascript"> 

         function displayContent() {
         var contentEntered = document.getElementById("userContent").value; 
         var contentEnteredSecond = document.getElementById("secondUserContent").value;
               document.getElementById("result").innerHTML += "<p> The content entered was " + contentEntered + " </p>"; 
               document.getElementById("result").innerHTML += "<p> The content entered was " + contentEnteredSecond + " </p>"; 
         }

      </script>
   </head>
   <body>
      <h1>Substring</h1>
      <div id="mainCont">
         <p>Please enter any content.</p>
         <p>Content:
            <input type="text" id="userContent">
         </p>
         <p>Content:
            <input type="text" id="secondUserContent">
         </p>
         <p>
            <input type="button" onclick="displayContent();" value="Submit">
         </p>
         <div id="result"></div>
      </div>
   </body>
</html>
function checkSub(str1, str2){

    if(str1.indexOf(str2) > -1 || str2.indexOf(str1) > -1) return true;
    else return false;
}

在ES6中,使用String.prototype.includes很简单:

str1.includes(str2) || str2.includes(str1);

You can use includes function from lodash library.

function checkSubstr(str1, str2) {
    return _.includes(str1, str2) || _.includes(str2, str1);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM