Below you’ll see a javascript/jQuery function I’m currently using:
var forward = new RegExp('forward'),
backward = new RegExp('backward'),
left = new RegExp('left'),
right = new RegExp('right');
if ( tweet.message.match(forward) ) {
console.log('forward');
body.addClass('forward');
bodyRemoveClass();
}
if ( tweet.message.match(backward) ) {
console.log('backward');
body.addClass('backward');
bodyRemoveClass();
}
if ( tweet.message.match(left) ) {
console.log('left');
body.addClass('left');
bodyRemoveClass();
}
if ( tweet.message.match(right) ) {
console.log('right');
body.addClass('right');
bodyRemoveClass();
}
Everything works just fine, but I’m not 100% happy with the way it’s written.
Basically what that does is, check if a given keyword (forward, backward, left or right)
are in a tweet (tweet.message)
I would like to know if there is a simple/cleaner way to achieve this.
Sorry but there is no online example…
Thank you
There’s no need to use
match()withRegexphere. You can do simple string matching withindexOf(). You can then avoid declaring all theRegexpat the beginning.However, this is much more neatly accomplished with an array of classes: