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
)?
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.
Here is the code for the 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
:
const code = document.getElementById("input").value;
Does this help?
You can generate a simple regex like this 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");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.