[英]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.
一个字段可以具有:
The sky is blue.
Second field have: The ocean is blue.
第二场有:
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? 在Javascript中,最简单的方法是检查在一个字段中输入的一个字符串是否是另一个字段的子字符串?
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.