Evaluating a string or object for compatibility

In my possession, I have a PHP array that has been encoded in JSON format:

<script>
var registeredEmails = <?php echo(json_encode($emails)); ?>;
</script>

To verify that this is functioning properly, I conduct the following test:

console.log(registeredEmails);
// This results in: ["<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bbd1d4d3d5fbdfd4d6dad2d595d8d4d6">[email protected]</a>", "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7d101c0f043d1912101c1413531e1210">[email protected]</a>"]

My objective now is to iterate through the JSON data and compare a specific 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 shows: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0c666364624c6863616d6562226f6361">[email protected]</a> is typeof: string

        //  $(this).val() holds a string from another source
        if (duplicate.test($(this).val())) {
            // A match has been found
        };
    }
}

It appears that the test() method is for checking string matches. I have checked and confirmed that my variable duplicate is a string, but it seems to still be recognized as an object. An error in JavaScript is returned:

Uncaught TypeError: Object <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2c464344426c4843414d4542024f4341">[email protected]</a> has no method 'test'

What could be the reason for this occurrence?

Answer №1

test() is a method that belongs to the RegEx object, and not the String object.

If you're looking to search within a string without using Regular Expressions, your best option would be to utilize String.search(). Alternatively, you can consider using String.indexOf().

Answer №2

When utilizing json_encode, it appears that your console output seems like an array. In this scenario, you may consider implementing the following solution:

var located = discover_match( registeredEmails, $(this).val() );

if( located ) {
   // found a match
}

function discover_match(collection, text) {

    for( var i = 0, length = collection.length; i < length ; i++ ) {
        if( collection[i].indexOf( text ) > -1 ) return true;
    }

    return false;
}​

Check out the Fiddle here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the significance of the error message "Uncaught (in promise) Object"?

I am facing an error in my code and need help to correct and debug it. I would like the code execution to halt when an issue arises. Here is my code snippet: export function postRequestOtpCode(phone: string, token: string): CancellableAxiosPromise { ax ...

Dividing an array of characters within an ng-repeat and assigning each character to its individual input tag

Hello, I'm currently learning Angular and I have a unique challenge. I want to take the names in a table and break each name into individual <input> tags, so that when a user clicks on a letter, only that letter is selected in the input tag. For ...

Exploring the functionality of the JavaScript switch statement across various condition scenarios

switch (true) { case (angle<20): console.log("case1") break; case (angle<70): console.log("case2") break; case (angle< ...

Issue encountered in AngularJS while configuring resources for the action `query`: Anticipated response was an object, but received an array instead

I've been attempting to utilize Angular 1.3 to access a REST service, but I keep encountering an error stating "Error: error:badcfg Response does not match configured parameter". My suspicion lies in the controller where I invoke $scope.data. Even th ...

The client is not displaying any events on the full calendar

I am currently working on creating a unique calendar display that showcases all the weekdays and events, regardless of the specific day in a month. The dates extracted from the database may seem "random", but in my C# code, I have devised a method to map e ...

Accessing a file url with Firefox using protractor

I am currently facing a challenge with Protractor as I try to access an HTML file as a website using it. Whenever I attempt to do so, I encounter an error from Protractor stating: Failed: Access to 'file:///C:/filelocation/index.html' from s ...

What is the best way to showcase my customized license plate on the following page?

I need help with incorporating my number plate builder into a website. I have utilized JQUERY and JAVASCRIPT for the styling aspect, but now I want to display the designed plate on the next page. Can someone guide me on how to achieve this using PHP, JQUER ...

Having difficulties accessing the properties of a dynamically created JSON object with ng-repeat functionality

Within an ng-repeat loop, I have implemented a radio button that assigns the entire person object to a scope variable as shown below: <li ng-repeat="person in people"> <label>{{person.name}} <input type="radio" ng-model="$parent.s ...

Is it possible to incorporate conditionals within a jade template using JavaScript?

I've been working on a Jade template that includes some logic, but I seem to be encountering an issue. Here's the code snippet: #container -for(var col=0; col < 2 ;col++){ - if(col % 4 == 0){ .movie_row - } ...

Am I causing my entire React component to re-render needlessly every time the state changes?

I've been attempting to develop an accordion component using React, but I seem to be encountering issues with the animation not functioning as expected. The approach I'm taking is quite standard - setting a max-height of 0 for each item body and ...

Challenge with maintaining tab view data in Openui5

I am facing an issue with my application's tabs. Each tab renders data retrieved through ajax calls from the database. However, whenever I switch between tabs, the data gets refreshed each time. Is there a way to prevent this refreshing behavior and i ...

Experiencing a Typescript issue while trying to set a string as the state of a React component with a specified TS type

I've defined a state in my React component for a specific data type called Color. \\ state const [messageSeverity, setMessageSeverity] = useState<Color>('success'); \\ TS type export type Color = 'success&ap ...

Ways to activate an event based on the dimensions (width/height) of

Exploring ways to implement an if statement based on specific width/height values using this code example. Check out the code snippet here My approach: <p id="confirmation">Try again!</p> <script> if (new dynamicSize.width() < ...

Tips for initiating a PHP class method through AJAX

As someone who is just starting to learn about ajax, I'm currently facing a challenge with calling the get_mother method through ajax in my form's textbox change event. My goal is to display the results in a datalist by using the following code. ...

Short-circuiting async flows on non-error events in Node.js

Node implements the CPS convention for callbacks. Typically, when a function encounters an error, it is common practice to either handle the error or callback the error to the parent function by utilizing something like return cb(err). One challenge I fac ...

Steps to load data using ajax-php with specific parameters

I have a situation where I need to trigger a JavaScript function when a link is clicked. <input type='hidden' id='name'> <a href='#' onclick='getUsers(1)'>Click here</a> function getUsers(id){ $( ...

The way an event can be outrun or vanish due to another event

let bar = new function(){ $scope.MessageSpan="Item added successfully";} When the Add button is clicked, the above function is invoked. However, if I want to hide this message when any other button is clicked, I would have to update the span text for all ...

The HTML anchor tag paired with the italic tag is a powerful combination for

Here is some example code: <a href="#"> <i class="some-bg" /> Some Text </a> Along with some Javascript: $("a").bind("touchstart", function (e) { e.preventDefault(); console.log("Tag: " + e.target); console.log("Tag Nam ...

Using the v-for directive to loop through a list of items and adding a v-autocomplete with

I am facing a challenge with using a dropdown menu within a loop to select the region for each office in my list of offices. The problem lies in passing the index value to the updateRegion method so that I can correctly associate the selected region with t ...

JavaScript transform numbers into array of buffers with a length of 4

I'm looking for a way to insert a numerical value into an array of 4 values [uint32_t] For example 255 should look like [0x00, 0x00, 0x00, 0xFF] I need to transmit this value from a Node.js server to an Arduino board Is there a built-in solution or ...