Hi I'm not that experienced in JavaScript, and I'm trying to parse commands given as full sentences. It has to be able to match the sentence to a function that will answer, and select sections that it will pass as arguments. I know that's not too clear so here's an example:
sentnce = "Show me a gift of a car"
commands = {
gif: {
pattern: "*gif of a [target]*"
action: gifMe(target)
This scenario should result in the call gifMe("a car") or even better, gimme could be called with a object containing all of the arguments specified, there may be more than just target. I have no idea how to go about coding this or searching for a method to do this. Thanks in advance.
It's not relevant (I think) but I'm using jquery and Coffeescript.
I think this is the code you are looking for. See the comment in the code for some more information about how it works.
var sentence = "Show me a gift of a car";
// specify commands
var commands = {
gif: {
pattern: /gift of a (.*).?/,
action: call
}
// you can add more commands here
}
// iterate over all commands
for(var key in commands)
{
// get settings for command
var settings = commands[key];
// apply command regex to sentence
var result = sentence.match( settings.pattern );
// if there is a match trigger the action with the word as argument
if( result && result.length > 1 )
settings.action.call(this, result[1]);
}
function call(value)
{
alert(value);
}