lol2x lol2x -4 years ago 378
Javascript Question

split string by space and new line in Javascript

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
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.

Answer Source

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

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


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 ] );    


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download