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.
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 .
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.
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.
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With