Separate a string into an array containing pairs of numbers

I'm currently working on splitting a hexadecimal string into an array of paired numbers. Here is the code snippet I have so far:

function getRGB(hexVal) {

    var substrHexVal = hexVal.substring(1,hexVal.length);

    var splitHexVal = substrHexVal.split("");

    return splitHexVal;

}

var result = getRGB("#00FF00");

result;

The current output looks like this:

["0", "0", "F", "F", "0", "0"]

However, I am aiming to achieve this output:

["00", "FF", "00"]

Although my intention might be clear, I would appreciate some guidance on how to proceed.

Answer №1

Discover the strength within the practical realm, Luke

b="#d1ffee"
"#d1ffee"

[2,4,6].map(function(o) {return b.slice(o,o+2)})
["d1", "ff", "ee"]

Answer №2

function extractRGB(hexValue) {

    return hexValue.toUpperCase().match(/[0-9A-F]{2}/g);

}

To obtain the hexadecimal pairs from a string, convert it to uppercase and use a basic regular expression for extraction. Although converting to uppercase is not essential, it ensures consistency in the extracted pairs. You can also opt to convert all alpha characters to lowercase instead (changing "A-F" to "a-f" in the regex):

function extractRGB(hexValue) {

    return hexValue.toLowerCase().match(/[0-9a-f]{2}/g);

}

If case sensitivity isn't a concern, you can make the regex case insensitive by adding the "i" modifier:

function extractRGB(hexValue) {

    return hexValue.match(/[0-9a-f]{2}/gi);

}

It's important to note that these functions do not guarantee returning 3 pairs. For example, passing "_?!@#$#00FF00FF" would result in ["00", "FF", "00", "FF"]. Similarly, providing "00FF0" would only give ["00", "FF"] due to finding 2 complete pairs.

In summary, consider incorporating error-checking measures.

Answer №3

One way to handle the string is by passing through it and inserting commas between pairs before splitting the string:

function extractRGB(hexValue) {
  var commaSeparated = '';

  // Removing the first character of the input string
  hexValue = hexValue.substring(1, hexValue.length);

  // Separating the pairs by comma
  for (var index = 0; index < hexValue.length; index++) {
    // Looping through each character of hexValue

    // Appending each character to commaSeparated
    commaSeparated += hexValue.charAt(index);

    // Adding a comma after every pair of characters, except for the last character
    commaSeparated += (index % 2 == 1 && index != (hexValue.length - 1)) ? ',' : '';
  }
  // Splitting the commaSeparated string by commas and returning the array
  return commaSeparated.split(',');
}

console.log(extractRGB("#00FF00"));    //  ["00", "FF", "00"]

Answer №4

function convertHexToRGB(hexColor) {
  var pattern = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i;
  hexColor = hexColor.replace(pattern, "$1,$2,$3");
  return hexColor.split(",");
}

It's important to validate input values and consider ways to optimize the code further, but this straightforward approach can achieve the desired outcome.

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

Search for documents in MongoDB that have a key that exists and the value is set to true

I'm currently working on developing a customized ACL for my application. The structure of my data is shown below: { _id: ObjectId("345sdf345dsf"), allowedResources: { "GET /auth": true, "POST /verify": false ...

Returning the user to the previous page after successfully submitting a web form on the current page in a .NET environment

Is there a simple way on a .net website to navigate a user back to the previous page they were on before submitting a form without needing a complex breadcrumb system? For example, imagine moving from Page1.aspx to Page2.aspx, which contains a form. Upon f ...

Cart Quantity Can Only Be Updated Once Using Ajax

I am currently facing an issue with my page that allows users to increase and decrease the quantity of a product in their cart before proceeding to the checkout confirmation page. I am using Ajax for this functionality, where the backend manipulates the qu ...

Unable to play GSM extension files on a web browser due to compatibility issues

I've been attempting to play an audio file with a (.gsm) extension using <audio>, object tags, and JavaScript. <script> var myAudio = new Audio(); // creating the audio object myAudio.src = "test.gsm"; // assigning the audio file t ...

Having trouble retrieving the value of the hidden field using ng-model

Hello, I'm currently learning AngularJS and facing some challenges with accessing hidden field values using ng-model. Specifically, I am working on an editing modal where I need to retrieve the ID for each record. Below is my controller code snippet: ...

Challenges arise when employing angular scope functions in the context of the DOM (html)

UPDATE: Encountered an issue caused by attempting to iterate over a function's return value using ng-repeat \ ng-options, rather than converting the data into a regular object through a promise. Here is the code snippet: $scope.layout.getParti ...

The issue arises in React Router DOM where the default routing does not function properly when incorporating conditional rendering

I need help with my React component that defines routes based on user roles. The issue I'm facing is that the default router * is not working as expected. I've tried rearranging the order of routes and using different combinations of the exact at ...

My initial junior UI/UX assignment: Can you confirm whether this form modal dialog is pixel-perfect, and offer any suggestions for improvements

Currently diving into my first project as a Junior UX/UI Designer. Coming from a background in software engineering, I decided to challenge myself by focusing on design. I'm seeking feedback on the pixel perfection of this modal window, which my seni ...

When working with NodeJS and an HTML form, I encountered an issue where the 'Endpoint'

Having trouble sending input data from a form to my nodejs endpoint. When I try printing the req.body, it shows up as undefined and I can't figure out why. Here is the relevant API code snippet: var bodyParser = require('body-parser') var e ...

php comparing two arrays with the similar_text function

I have collected two extensive arrays of product names and prices through scraping, resembling the following: $one=array('grape'=>'0.40','apple'=>'1.20','banana'=>'1.80','lemon&apos ...

NodeJS Like/Dislike System: Leveraging the Power of NodeJS

(Please refer to my solution in the answer post below) Hello there! Today, I have a question about implementing a like/dislike system using nodeJs with data stored in MongoDB. What is the current scenario? I'm tasked with creating the backend for ...

Is it true that loading "undefined" into an array can use up a significant amount of memory?

I've encountered a strange issue where a bug is consuming excessive memory and leading to frequent server crashes. Every 30 seconds, a value is saved to an array: historicalValues.push( valueToSave ) When valueToSave is set to 1, the memory usage r ...

Dealing with errors in Node.js using the Express framework and the

The code I'm having trouble with is shown below app.get('/', function(req, res, next) { if (id==8) { res.send('0e'); } else { next(); } }); app.use(function(err, req, res, next){ res.send(500, ' ...

The Ajax function is not defined and results in a runtime error being thrown

customAjax.postJson( "/foo/GetFoo", { fooName: fooName }, function (data) { }, function (error) { }); }; My Rest api call is GetAsync() It throws customAjax is unde ...

Having trouble getting the jQuery autocomplete feature to function properly?

On my page, there is a button labeled "Add a Skill." Clicking on this button should trigger the display of an input box where you can enter your skill, another input box for your skill level, and a horizontal slider to select the skill level. In my databa ...

Tips for troubleshooting Grunt in PHPStorm (or WebStorm)

Looking for tips on debugging grunt, such as using an event listener function, in PHP Storm. Does anyone have any ideas? I know that PHP Storm has Node.js support, but I'm not sure how to configure debug settings for debugging a grunt task. For examp ...

Remove the option to delete without making any changes to the flash file

Utilizing the DataTable javascript tool to export a grid, I have obtained the following HTML generated code: <div class="DTTT_container"> <a class="DTTT_button DTTT_button_copy" id="ToolTables_example_0" tabindex="0" aria-controls="e ...

What is the best method to verify chrome.runtime.onInstalled in Chrome extension testing?

Is there a way to test the chrome.runtime.onInstalled handler? I am developing a Chrome extension that utilizes chrome storage to store specific data. In my upcoming release, I plan on making changes to the data model in chrome storage. To do this effectiv ...

Removing a similar object from an array using JavaScript

Working on a d3 force graph, I aimed for smooth updates using the method shown in the Modifying a Force Layout example. However, my goal was to achieve dynamic updating behavior unlike the static example provided. After calling initializeGraphData(json); i ...

Introducing a fresh Backbone object attribute that points to an existing instance property

While working with Backbone/Marionette, I came across something unusual. When I create a new instance of a view with a new collection property and then create another instance of the same view, it seems that the collection property of the second view point ...