[英]How to check if a javascript string is between two other strings
假設我有一個這樣的字符串:
let string = "one two three four five red five six seven eight nine"
我怎么能返回一個布爾值( true
或false
),告訴用戶red
是否在兩個單詞five
之間(在這種情況下,布爾值true
將返回,因為red
在兩個fives
之間)?
我使用此代碼的示例
我正在制作一個文本編輯器,用戶可以在其中在文本區域中鍵入代碼。
我將把文本編輯器的值作為變量返回。 我想檢查用戶是否在兩個<script>
標簽內輸入代碼。
這是textarea
的代碼:
<textarea class="form-control slideIn" id="input" spellcheck="false" wrap="off" placeholder="Get Creative!"></textarea>
此代碼獲取textarea
的值:
const code = document.getElementById("input").value;
這有幫助嗎?
您可以生成一個簡單的正則表達式,例如 one five(.*)five
通過一些配置,它可能會變得像
function isBetween(mystring, between, left, right)
{
// define the regex which will become : "/five(.*)five/g"
const regex = new RegExp( left + ' (.*) ' + right, 'g');
// execute the regex
const m = regex.exec(mystring);
// if there is a result and the (.*) pattern matched sthg
// then check if its equel to red
return m && m[1] ? (m[1] === between) : false;
}
isBetween("one two three four five red five six seven eight nine", "red", "five", "five");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.