Reputation: 9
I tried searching for this, but the results coming up were mostly PHP which had a simple json_decode to make an array etc.
Sadly it seemed (unless I didn't see it) like javascript didn't have this function.
Anywhom, my problem is that I have this relatively small json document that looks like this:
{
"greetings" : [
"hey",
"sup",
"hello",
"hola",
"yo",
"howdy",
"hi",
"hello bot"
]
}
(There's more than that in the entire JSON, but this is really all we need)
I would like to, using javascript, check if any of these are present in my message as shown below:
function isGreeting(message) {
return DICT.greetings.indexOf(message) != -1;
}
var re = '/\b' + DICT.greetings.indexOf(message) + '\b/i';
if (isGreeting(message)) {
console.log(message.search(re));
}
Currently it SOMEHOW works, it detects the greetings if they are not in capitals, but I would like them to be detected no matter how it's written, as shown by my attempt with regex.
How would I go about, that no matter how you greet it (as long as, of course, it is on the list) with any kind of capitals, it would log it? So "Hey" would still log, even if the JSON only says "hey" etc.
Upvotes: 0
Views: 136
Reputation: 1
function isGreeting(message) {
var message = new RegExp(message, "gi");
var DICT = {
"greetings" : [
"hey",
"sup",
"hello",
"hola",
"yo",
"howdy",
"hi",
"hello bot"
]
};
return message.test(DICT.greetings);
};
isGreeting("Hi"); // true
Upvotes: 1
Reputation: 46841
How would I go about, that no matter how you greet it (as long as, of course, it is on the list) with any kind of capitals, it would log it?
Try with JavaScript String toLowerCase() Method or JavaScript String toUpperCase() Method.
Convert the message in either case based on DICT.greetings
case then check it using indexOf()
method inside isGreeting
method.
Since it's a JSON string, so you can try with jquery.parsejson() as well that takes a well-formed JSON string and returns the resulting JavaScript object.
For e.g:
var obj = jQuery.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" );
Upvotes: 1
Reputation: 51330
One easy way:
DICT.greetings.indexOf(message.toLowerCase()) != -1
No regexes required, and it's more readable.
If you insist on using regex for word boundaries for instance, then I suggest you escape the possible values first. Then, your problem was with \b
, which has to be \\b
inside a quoted string, and you should have used the RegExp object.
var re = DICT.greetings.indexOf(message).replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
re = new Regex('\\b' + re + '\\b', 'i');
re.test("Hey") // true
Upvotes: 1