3

I'm trying to split a string in two parts with the separators "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?

dda
  • 6,030
  • 2
  • 25
  • 34
Björn C
  • 3,860
  • 10
  • 46
  • 85
  • Possible duplicate of [how to find a number in a string using javascript](http://stackoverflow.com/questions/1623221/how-to-find-a-number-in-a-string-using-javascript) – Mihir Kale May 31 '16 at 07:07

6 Answers6

12

You could use a regular expression with a positive 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));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
3

You can use .match() with RegExp /\d+\.\d+/g

console.log("T49.80000305175781L60.00000190734863".match(/\d+\.\d+/g))
guest271314
  • 1
  • 15
  • 104
  • 177
1

Split takes two optional arguments. First one is the delimiter while the second one is the limit. You can find here the documentation.

If you want to split it with multiple delimiters you should use a regex:

console.log('T49.80000305175781L60.00000190734863'.split(/T|L/));
George Karanikas
  • 1,244
  • 1
  • 12
  • 38
1

Ninas answer is great! I really mean it. But just to make it interesting if you would have more of these numbers/arrays or what ever you want to call it you could use a similar way like Nina, but use regular expression for letters to get all the values without the need to declare all of the letters.

With the letters included:

console.log('T49.80000305175781L60.00000190734863C34.534623460304040003'.split(/(?=[a-zA-Z])/));

Without the letters:

console.log('T49.80000305175781L60.00000190734863C34.534623460304040003'.split(/[a-zA-Z]/));
thepio
  • 6,193
  • 5
  • 35
  • 54
1

I don't think you can use split with multiple separators like that.

What you can do is use a regular expression to split the string.

xPos.split(/T|L/g)

should work.

Jordan Rhea
  • 1,186
  • 15
  • 34
0

Just replace the character with blank character and store that string into new variable. You will get all the number