Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split string by space and new line in Javascript [closed]

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.

like image 428
lol2x Avatar asked Jun 24 '13 08:06

lol2x


People also ask

How do you break a string in a new line?

newStr = splitlines( str ) splits str at newline characters and returns the result as the output array newStr . splitlines splits at actual newline characters, not at the literal \n . To split a string that contains \n , first use compose and then use splitlines .

Does JavaScript treat newline as space?

replace(/\n/g, " "); Note that you need the g flag on the regular expression to get replace to replace all the newlines with a space rather than just the first one. Also, note that you have to assign the result of the . replace() to a variable because it returns a new string.

How do you split a string in space?

To split a string with space as delimiter in Java, call split() method on the string object, with space " " passed as argument to the split() method. The method returns a String Array with the splits as elements in the array.

How can I split a string into two JavaScript?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.


1 Answers

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/

like image 70
JJJ Avatar answered Sep 30 '22 06:09

JJJ