I have a JSON-encoded PHP array:
<script>
var registeredEmails = <?php echo(json_encode($emails)); ?>;
</script>
To check that this works, I do this:
console.log(registeredEmails);
// this outputs: ["john@domain.com", "mary@domain.com"]
And now I would like to iterate through that JSON and test a certain string against all the strings it contains.
for (var email in registeredEmails) {
if (registeredEmails.hasOwnProperty(email)) {
var duplicate = registeredEmails[email];
console.log(duplicate + ' is typeof: ' + typeof(duplicate));
// this outputs: john@domain.com is typeof: string
// $(this).val() is a string from somewhere else
if (duplicate.test($(this).val())) {
// we found a match
};
}
}
As I understand it, the test() method tests for matches on strings. I’ve tested to make sure that my variable duplicate is a string, but apparently it’s still an object. I’m given the following JS error:
Uncaught TypeError: Object john@domain.com has no method 'test'
Why is that?
test()is a method of the RegEx object, not String.Your best bet would probably be to use
String.search()instead. You could also probably useString.indexOf()if you’re not trying to use Regular Expression matching.