extract information from a JavaScript string

I have a sequence that looks like this:

coordinates = '15,-2,-3,15'

This sequence corresponds to points, specifically A(15, -2), B(-3, 15).

Q How can you retrieve the data from a string in this format?

It would be ideal to obtain the results as an array of a custom structure (e.g., point[i].x, point[i].y), but using a multidimensional array is also acceptable (e.g. point[i][0], point[i][1]).

Answer №1

When utilizing the split method, it will transform the values into strings, necessitating the use of parseInt() or parseFloat() to revert them back to numbers.

For a direct approach to extracting the numbers without converting them into an object first, leverage the capabilities of JSON.parse

let positions = '15,-2,-3,15';
let arrPositions = JSON.parse("[" + positions + "]");
FunctionA(arrPositions[0], arrPositions[1]); 
FunctionB(arrPositions[2], arrPositions[3]);

Answer №2

To implement this method, start by breaking down the string into separate parts using commas as separators. Then, iterate through each part to create a Point object with x and y coordinates.

var rawData = positions.split(','); 
var pointsList = [];
for(var j = 0; j < rawData.length - 1; j++) {
    var coordX = rawData[j];
    var coordY = rawData[++j];
    pointsList.push(new Point(coordX,coordY));
}

Answer №3

If I were to take action, it would likely involve:

coordinates = '8,-5,-6,18';

Array = [];
loc = coordinates.split(',');
index = 0;
while( loc.length ){
    Array[index++] = loc.splice( 0, 2 );
}

Answer №4

Just for fun:

(function customFunction (elem, str, params, result) {
     result = elem.exec(str);
     return result ? [params(result[1], result[2])].concat(customFunction(elem, str, params)) : [];
 }(/(-?\d+),(-?\d+)/g, '15,-2,-3,15',
   function (num1, num2) { return { number1: num1, number2: num2 }; }));

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

Determine the maximum size of a specified number of square divs that can fit within responsive parent divs

I am working on creating a grid of square divs inside a container with variable height and width. The number of square div's is predetermined. All square divs will have images with the same dimensions (similar to the example). They should align left ...

What is the best way to compare all the elements in an array to the entries in another object, while also storing the results of each comparison?

I am working with a JSON file that contains an array of 2 objects: `{ bg: 'a', o: 'c' }`, `{hg': 'a2', 'oo': 'c3'}`. My goal is to compare each object in the array with another object structured as fol ...

Hide panel when button is clicked - bootstrap

Is it possible to make a panel collapse by clicking a regular bootstrap button? Below is the code snippet: <div class="panel panel-primary" style="border-color: #464646;"> <div class="panel-heading" style="border-color: #BBBBBB; height: 35px; ...

The benefits of using Node.js for asynchronous calls

Each time a new data is added or existing data is updated, the variables new_data and updated_data will increment accordingly. However, when attempting to output the total count of new_data and updated_data at the end of the code, it always shows as 0. H ...

The array containing prime numbers fails to display its contents accurately

Having encountered some challenges with an array in Java, my goal was to utilize threads to store prime numbers in an array. Despite my efforts, it seems that the implementation is not working as expected. The objective here is for b[c] to contain all prim ...

Exploring the advantages of utilizing macros in C for defining arrays

I'm a beginner in C programming and currently working on coding for a Nordic nrf52 chip. While I believe my issue lies within general C knowledge rather than the application itself. My problem arises when setting up an array of structs using pre-defi ...

Tips for inserting List data using ajax

I am working with two entities in a 1:N relationship. An entity contains a list of Bentity objects: List<Bentity> getList = new ArrayList<>(); I need to send data from JSP using AJAX. var data={ a:1, b:2, getList[0].abcdKey:1 } $.post ...

Is there a way to create a fading effect for background images using jQuery?

Is there a way to animate the background-image of an element with fadein and fadeout effects on hover? ...

What is the best way to deserialize an array containing both double and integer data types in C# using MsgPack?

Msgpack-c offers me arrays as objects. Let's say I serialize a C++ message like this: template <class T> struct Message { std::vector<T> data; std::vector<int> shape; MSGPACK_DEFINE(data, ...

Issue with sliding out in jQuery

Facing a problem with my jQuery animations. Successfully implemented the slide in effect for my flex sidebars, but struggling with the slide out effects. The slide out function is causing the sidebars to vanish instantly. I think I need to incorporate the ...

What's the best way to ensure that the iframe resolution adjusts dynamically to perfectly fit within its container?

iframe-screenshot Displayed in the image are two iframes, but at times I may need to display three. The aim is to ensure that all iframes are responsive within their containers. Below is my existing CSS styling: iframe { width: 100%; height: 1 ...

Accessing information via a PHP script with the help of AJAX and jQuery

In the process of developing a gallery feature that displays a full image in a tooltip when hovering over thumbnails, I encountered an issue where the full images extended beyond the viewfinder. To address this, I decided to adjust the tooltip position bas ...

The JQuery function will only execute after the alert within the success function has been triggered

After adding an alert following $('#add_new').trigger('click');, the statements below it work as expected. However, without the alert, the following statements do not seem to work. It appears that the trigger event may not have complete ...

Assigning an enum value from TypeScript to another enum value

One of the functions I've written is named saveTask type Task = string; enum Priority { Low = "Low", Medium = "Medium", High = "High", } enum Label { Low = "Low", Med = "Med", High = " ...

What is the way to bypass certificate validation when making a Fetch API request in the browser?

The code snippet below is currently being executed in the browser: const response = await fetch(`${url}`, { method: 'POST', headers: { Authorization: `Basic ${authorization}`, }, body: loginData, }) Upon calling this co ...

AngularJS directive that offers dynamic functionality

Currently, I am working on dynamically inserting an ng-options directive within various <select> elements throughout my application. These elements have their own unique class names and other directives, such as ng-if, among others. <div ng-app=" ...

Working with arrays and elements in JavaScript using regular expressions

The programming language is JavaScript. Imagine we have an array filled with positive and negative integers mixed in with other letters (e.g. 1a or -2d). The challenge is to figure out how to select all the strings that start with or contain positive inte ...

The resetFields() function fails to execute

While utilizing Vue3 with Element Plus to create a form, I encountered an issue with the resetFields() method not working as expected. The form is unable to automatically refresh itself. In the child component (Edit.vue): <template> <el-dialo ...

Testing javascript components with Jasmine-Karma: A guide to mocking variables within a function

Function that requires testing: function validate() { var isOk = false; var radios = $('input[name="abc"]:checked', '#parentDiv'). val() ; If(radios === "ok" ) isOk = true; return isOk; } I am looking to ...

Navigating with Vue Router: Automatically redirecting to the homepage upon completion of registration

I have successfully completed the creation of the user registration form. Once the sign-up process is finished, my goal is to have the page redirect back to the home page. I have now integrated vue-router using the vue CLI command. Initially, I tried pl ...