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.

2
  • 2
    There is no way you are allowed to have those constructs to begin with in JS so you need to first show valid JavaScript. Commented Jun 24, 2013 at 8:48
  • 1
    duplicate: stackoverflow.com/questions/96428/… Commented Jun 24, 2013 at 8:51

4 Answers 4

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/

Sign up to request clarification or add additional context in comments.

3 Comments

And if I want to chack that values X Y are numbers? I am trying something like that: example but it doesn't work :/ I have void 0
And (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
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 ...

Comments

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/

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.