简体   繁体   English

如何检查一个javascript字符串是否在其他两个字符串之间

[英]How to check if a javascript string is between two other strings

Lets say I had a string like so:假设我有一个这样的字符串:

let string = "one two three four five red five six seven eight nine"

How could I return a boolean (either true or false ) that tells the user if the word red is between the two words five (In this case a boolean of true would be returned as red is between the two fives )?我怎么能返回一个布尔值( truefalse ),告诉用户red是否在两个单词five之间(在这种情况下,布尔值true将返回,因为red在两个fives之间)?

Example where I am using this code我使用此代码的示例

I am making a text editor where the user types code in a text area.我正在制作一个文本编辑器,用户可以在其中在文本区域中键入代码。

I am going to return the value of the text editor as a variable.我将把文本编辑器的值作为变量返回。 I would like to check if the user is inputting code within two <script> tags.我想检查用户是否在两个<script>标签内输入代码。

Here is the code for the textarea :这是textarea的代码:

<textarea class="form-control slideIn" id="input" spellcheck="false" wrap="off" placeholder="Get Creative!"></textarea>

And this code gets the value of the textarea :此代码获取textarea的值:

const code = document.getElementById("input").value;

Does this help?这有帮助吗?

You can generate a simple regex like this one five(.*)five您可以生成一个简单的正则表达式,例如 one five(.*)five

With a bit of configuration, it could become something like通过一些配置,它可能会变得像


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