30

I am trying to split values in string, for example I have a string:

var example = "X Y\nX1 Y1\nX2 Y2"

and I want to separate it by spaces and \n so I want to get something like that:

var 1 = X
var 2 = Y
var 3 = X1
var 4 = Y1

And is it possible to check that after the value X I have an Y? I mean X and Y are Lat and Lon so I need both values.

AndrewL64
  • 15,794
  • 8
  • 47
  • 79
lol2x
  • 441
  • 2
  • 5
  • 14

4 Answers4

57

You can replace newlines with spaces and then split by space (or vice versa).

example.replace( /\n/g, " " ).split( " " )

Demo: http://jsfiddle.net/fzYe7/

If you need to validate the string first, it might be easier to first split by newline, loop through the result and validate each string with a regex that splits the string at the same time:

var example = "X Y\nX1 Y1\nX2 Y2";
var coordinates = example.split( "\n" );
var results = [];

for( var i = 0; i < coordinates.length; ++i ) {
    var check = coordinates[ i ].match( /(X.*) (Y.*)/ ); 

    if( !check ) {
        throw new Error( "Invalid coordinates: " + coordinates[ i ] );
    }

    results.push( check[ 1 ] );
    results.push( check[ 2 ] );    
}

Demo: http://jsfiddle.net/fzYe7/1/

JJJ
  • 32,902
  • 20
  • 89
  • 102
  • And if I want to chack that values X Y are numbers? I am trying something like that: [example](http://jsfiddle.net/fzYe7/3/) but it doesn't work :/ I have void 0 – lol2x Jun 24 '13 at 10:26
  • http://jsfiddle.net/fzYe7/4/ – JJJ Jun 24 '13 at 10:28
  • And (http://jsfiddle.net/fzYe7/7/) if I want to save each number value into vars (in loop ofc because i dont know how many coordinates i will get) is it possible to save 1st number into X* and 2nd into Y* ? * is a number – lol2x Jun 24 '13 at 11:30
15

var string = "x y\nx1 y1\nx2 y2";
var array = string.match(/[^\s]+/g);

console.log(array); 

jsfiddle: http://jsfiddle.net/fnPR8/

it will break your string into an array of words then you'd have to iterate over it ...

Evgeny Bobkin
  • 4,092
  • 2
  • 17
  • 21
gmaliar
  • 5,294
  • 1
  • 28
  • 36
7

Use a regex to split the String literal by all whitespace.

var example = "X Y \nX1 Y1 \nX2 Y2";
var tokens = example.split(/\s+/g);

console.log(tokens.length);
for(var x = 0; x < tokens.length; x++){
   console.log(tokens[x]);
}

Working Example http://jsfiddle.net/GJ4bw/

Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189
1

you can split it by new char first and store it in an array and then you can split it by spcae.

following may give a referance Link

Community
  • 1
  • 1
dev2d
  • 4,245
  • 3
  • 31
  • 54