user12059608
user12059608

Reputation:

How to split a string into an array at a given character (Javascript)

var stringToSplit = "10000.9409.13924.11025.10000._.11025.13225._.9801.12321.12321.11664.";

//Finished result should be:
result == ["10000.", "9409.", "13924.", "11025.", "10000.", "_.", "11025.", "13225.", "_.", "9801.", "12321.", "12321.", "11664."]

After each "." I want to split it and push it into an array.

Upvotes: 0

Views: 75

Answers (5)

arizafar
arizafar

Reputation: 3132

you could use a lookbehind with .split

var stringToSplit = "10000.9409.13924.11025.10000._.11025.13225._.9801.12321.12321.11664.";
let out = stringToSplit.split(/(?<=\.)/);
console.log(out)

Upvotes: 1

brk
brk

Reputation: 50346

split the string using . delimiter and then slice to remove the last empty space. Then use map to return the required array of elements

var stringToSplit = "10000.9409.13924.11025.10000._.11025.13225._.9801.12321.12321.11664.";
let newData = stringToSplit.split('.');
let val = newData.slice(0, newData.length - 1).map(item => `${item}.`)
console.log(val)

Upvotes: 1

Argee
Argee

Reputation: 1224

var stringToSplit = "10000.9409.13924.11025.10000._.11025.13225._.9801.12321.12321.11664.";

var arr = stringToSplit.split(".").map(item => item+".");

console.log(arr);

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386868

You could match the parts, instead of using split.

var string = "10000.9409.13924.11025.10000._.11025.13225._.9801.12321.12321.11664.",
    result = string.match(/[^.]+\./g);

console.log(result);

Upvotes: 1

Ilijanovic
Ilijanovic

Reputation: 14924

You split it, and map over. With every iteration you add an . to the end

var stringToSplit = "10000.9409.13924.11025.10000._.11025.13225._.9801.12321.12321.11664.";

let result = stringToSplit.split(".").map(el => el + ".");

console.log(result)

Upvotes: 2

Related Questions