PFC
PFC

Reputation: 15

Javascript : How can I put this data in better way ? (string to array/object)

I have a string that could look like this :

str = "4bobsCat3carsOfThisGarage10this1that0whatever";

My string always starts with a number from 0 to 99, I have multiple character chains made up of lower and upper case letters separated by numbers from 0 to 99. This string is basically :

This pattern repeats itself a couple times. I want to create an object/array to class this weird kind of data in a better way ... It would be great if I could get something like :

array = [4, "bobsCat", 3, "carsOfThisGarage", 10, "this", 1, "that", 0, "whatever"]

Or like this :

object["bobsCat"] = {number : 4};
object["carsOfThisGarage"] = {number : 3};
object["this"] = {number : 10};
object["that"] = {number : 1};
object["whatever"] = {number : 0}

Thanks !

Upvotes: 1

Views: 53

Answers (3)

trincot
trincot

Reputation: 350270

To get the second object structure, you could use the new method matchAll, and unary plus operator to convert the digits to number type:

let str = "4bobsCat3carsOfThisGarage10this1that0whatever";

let obj = {};
for (let [, dig, key] of str.matchAll(/(\d+)(\D+)/g)) {
    obj[key] = { number: +dig };
}

console.log(obj);

Upvotes: 1

Oron Bendavid
Oron Bendavid

Reputation: 1533

Try this one:

str.split(/(\d+)/)

You can also remove empty strings ("") by:

str.split(/(\d+)/).filter(Boolean)

Upvotes: 0

Shane
Shane

Reputation: 1216

You can do it with a regex

let str = "4bobsCat3carsOfThisGarage10this1that0whatever";
let rx = /(\d{1,2})([a-zA-Z]+)/g;

var rxResult = null;
while (rxResult = rx.exec(str)) {
    // rxResult[1] will be your number
    // rxResult[2] will be text
    console.log(rxResult[1], rxResult[2]);
}

Upvotes: 2

Related Questions