简体   繁体   中英

If text before word is specific word

If I had the string

"Nice to meet you"

Would there be a way to check if the word before "you" was "meet", and return a Boolean value? (eg if word before you == meet)

ES6 or above only solution:

Use String.prototype.includes . Regex is overkill for this type of thing.

Use string.includes("meet you")

Are you looking for Regular expressions, OP? With regular expressions you can do much more than just checking if a particular word appears before another in a string. You can check if there is another word in between them for example.

Would something like this satisfy your needs? The regex returns true if the word you appears after meet with anything/nothing in between them.

let hay = "Nice to meet you";
let needle = /meet.*you/;
if( needle.test(hay) ) {
    // yes it does
}

You can find explanations of RegEx in JS on MDN page: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

Yes, it would be.

 var string = "Nice to meet you",
     split = string.split(" "),
     answer = split[split.indexOf("you") - 1] == "meet";

console.log('"Meet" is before "you"?', answer);

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM