簡體   English   中英

如何檢查一個javascript字符串是否在其他兩個字符串之間

[英]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"

我怎么能返回一個布爾值( truefalse ),告訴用戶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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM