29

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.

4

4 回答 4

54

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/

于 2013-06-24T08:56:10.050 回答
13

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

于 2013-06-24T08:50:47.610 回答
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/

于 2013-06-24T09:01:35.937 回答
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

于 2013-06-24T08:49:12.173 回答