Mjukis Mjukis - 2 months ago 7
Javascript Question

How to find numbers in the following string using JavaScript?

I'm trying to split a string in two parts with the seperators "T" & "L".

T49.80000305175781L60.00000190734863


So, I'm expecting an array with these elements ["49.80000305175781","60.00000190734863"]

I have tried these but they don't work.

var xPos = xPos.split('T', 'L'); //Returns empty
var xPos = xPos.split(/T/, /L/); //Returns empty
var xPos = xPos.split(/T/); //Returns: ["", "49.80000305175781L60.00000190734863"]


What should be the best approach?

Answer

You could use a regular expression with a positve lookahead.

console.log('T49.80000305175781L60.00000190734863'.split(/(?=[TL])/));

Or without the letters, just a split where the letters appears.

console.log('T49.80000305175781L60.00000190734863'.split(/[TL]/));

Just for completeness, a proposal with String.match in a single step

console.log('T49.80000305175781L60.00000190734863'.match(/[^TL]+/g));