繁体   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