Split string with JavaScript

111,251

Solution 1

Assuming you're using jQuery..

var input = '19 51 2.108997\n20 47 2.1089';
var lines = input.split('\n');
var output = '';
$.each(lines, function(key, line) {
    var parts = line.split(' ');
    output += '<span>' + parts[0] + ' ' + parts[1] + '</span><span>' + parts[2] + '</span>\n';
});
$(output).appendTo('body');

Solution 2

Like this:

var myString = "19 51 2.108997";
var stringParts = myString.split(" ");
var html = "<span>" + stringParts[0] + " " + stringParts[1] + "</span> <span>" + stringParts[2] + "</span";
Share:
111,251
Admin
Author by

Admin

Updated on November 25, 2020

Comments

  • Admin
    Admin over 3 years

    how to parse this string with java script

    19 51 2.108997
    20 47 2.1089

    like this

    <span>19 51</span> <span>2.108997</span>     
    <span>20 47</span> <span>2.1089</span>
    
  • Dzhuneyt
    Dzhuneyt over 11 years
    Also, note that the lines variable will be a zero-based array after the second line, so you can access individual elements that were matched (each newline in the above example) in the following manner: lines[0], lines[1] and so on.