[英]Determining if one of the two strings is a substring of the other String Javascript?
假設我有兩個文本字段,用戶可以在其中輸入任何文本。
一個字段可以具有: The sky is blue.
第二場有: The ocean is blue.
在Javascript中,最簡單的方法是檢查在一個字段中輸入的一個字符串是否是另一個字段的子字符串?
到目前為止,這就是我所擁有的:
<!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.