Determine if a specific string is present in any of the values within an array by utilizing

A scenario: I have a cookie that has been split into an array:

var treats = document.cookie.split(';');
[dogs=bla, cats=sdfgh, cabbages=kjhgfdfg]

If I aim to locate the index of 'cats=sdfgh', I can utilize

treats.indexOf('cats=sdfgh');
1

However, if my goal is to determine whether the value of cats has been set, how do I go about it? Would treats.indexOf(find('cat=')); or a similar approach work?

Hence, minus knowledge of the cats' value, how do I ascertain its existence in the cookie?

Additionally, what's the technique to acquire the index number of that specific cookie?

Answer №1

If you want to extract a value from a cookie, you can use a simple regular expression like this:

if(value = document.cookie.match(/(^cats=|;cats=)([^;]+)/)){
    console.log(value);
}

This will return an array where the third element is your desired value if it's found :)

JSFIDDLE

Alternatively, if you don't need to support outdated browsers, consider checking out the MDN cookie framework mentioned in the comments.

Answer №2

If you want to locate the initial corresponding value in an array, you can utilize the Array.prototype.some method:

var cookies = document.cookie.split(';'); // ["dogs=bla", "cats=sdfgh", "cabbages=kjhgfdfg"]

var matchFound = cookies.some(function(cookie) {
    return cookie.indexOf('cats') == 0;
}); // => true

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

The dynamic functionality of the Bootstrap React Modal Component seems to be malfunctioning

I'm encountering an issue with React Bootstrap. I'm using the map function in JavaScript to iterate through admins. While all values outside the modal display correctly from the admins array, inside the modal only one standard object from the arr ...

Solving the Problem of Input Values with Jquery and Javascript

I am facing a challenge in making a div vanish with the class 'backarea' while simultaneously displaying another div with the class 'successLog' on the screen. The catch here is that I want this transition to occur only when specific us ...

Utilize this JavaScript tool to effortlessly transform an XML string into JSON format

Looking for the optimal javascript function, plugin, or library to effectively transform an XML string into JSON format. One tool I came across is , but unfortunately, it struggles with strings that begin with 0. For example, 005321 may end up converted t ...

Updating Bootstrap Indicators with jQuery on Click Event

Unfortunately, I am unable to share an image due to limited internet data. My goal is to switch each image to its sprite equivalent. There are three list items that I'm struggling to change because they each have two classes that need to be updated. ...

What's the reason behind the refusal of my connection to localhost at port 3000 in Node.JS?

As a student venturing into the world of back-end development for the first time, I decided to dive into learning Node.JS. To kick things off, I downloaded a PDF book titled "Jumpstart Node.JS" from SitePoint. Following the provided instructions, I attempt ...

Is it possible to change button behavior based on input values when hovering?

Currently, I am attempting to create a webpage where users can input two colors and then when they press the button, a gradient of those two colors will appear on the button itself. <!doctype html> <html> <head> <script src=&apos ...

Explore various queries and paths within MongoDB Atlas Search

I am currently working on developing an API that can return search results based on multiple parameters. So far, I have been able to successfully query one parameter. For example, here is a sample URL: http://localhost:3000/api/search?term=javascript& ...

What is the method for executing code in HTML without needing a beginning or ending tag?

I have created a code that creates a shape which alternates between the colors green and blue, along with changing text from 'Hi' to 'Hello' when a button is clicked. Now, I am looking for a way to make this transition happen automatica ...

How can I send a variable into the DOM using AJAX?

Apologies for posting a question earlier about creating a condition for checkbox without proper investigation. It appears that I need to pass my variables here. function setsession(sessionid, action, data) { $("#totalselection").show(); $. ...

Utilize the grouping functionality provided by the Lodash module

I successfully utilized the lodash module to group my data, demonstrated in the code snippet below: export class DtoTransactionCategory { categoryName: String; totalPrice: number; } Using groupBy function: import { groupBy} from 'lodash&apo ...

Preventing Unwanted Scroll with jQuery

I'm currently working on a project where I have several description blocks that are meant to fade in when the corresponding image is clicked. The fading effect works fine, but there's an issue with the page scrolling up each time a new image is c ...

How can I run JavaScript code written in the Chrome console on standalone Node.js platform

After successfully creating a script that functions when input into the Google Chrome developer console, I now desire to convert it into an executable file. My goal is to open the file and have it log all activity in a separate node.js console window, whil ...

Manage shared nested modules across different modules in Vuex without redundancy

In my Vue.js application, I am using Vuex as the state manager. To ensure that certain states are shared across different components, I have created a nested state containing all the common information. This allows me to import it into multiple modules. F ...

Using react-select to display "N items selected" instead of listing out all the selected items

Exploring the potential of react-select as a city-picker selector for users to choose one or multiple cities to filter data. Take a look at how it appears on my page: https://i.sstatic.net/A3cBX.png The list of cities may be extensive, and I am concerned ...

Existing cookie is not defined when using ngCookies

I've been trying to solve this issue for hours now but haven't been able to figure out the cause. Essentially, I have a frontend built with Angular.js that attempts to log users in using ngCookies on Angular.js 1.3.15 and communicates with an au ...

Learning to Use jQuery to Send JSON Requests in Rails

I am attempting to send a JSON post request to a Rails 3 server. Here is the AJAX request I have set up: $.ajax({ type: 'POST',<br> contentType: "application/json",<br> url: url, ...

Using Twig: Transfer the content of a textfield as a parameter in the routing

I have a task of redirecting to another page while passing along the value from a textfield. Here is my current code: {% extends "base.html.twig" %} {% block body %} <button onclick="host()">Host the session</button> <button onclic ...

The curious conduct of wild safari creatures

I have been using JavaScript to split my ePub chapter into pages by wrapping the code with new divs that represent separate pages. I have also created CSS styles for these new divs. Everything works perfectly when the file has a filename extension of &apos ...

Issue with module.exports entry in Webpack configuration causing errors

I've been working on setting up webpack but I've hit a roadblock due to this error message. It seems like there's an issue with the entry configuration. When I try to add it without specifying a path, as shown in the tutorial, I receive the ...

Transitioning from a traditional CURL method to utilizing AJAX and XMLHttp

I'm currently facing a challenge converting the curl code from an API named TextRazor to AJAX XMLHttp due to limitations on the platform I am working with. Despite trying various solutions shared by the community, I have been unsuccessful in retrievin ...