7

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>
Taryn East
  • 27,486
  • 9
  • 86
  • 108
mr heLL
  • 109
  • 1
  • 1
  • 4
  • 2
    Did you make a typo? I can't find a proper relation. How did 19 51 become 20 46? or is that not important? – JohnP Jan 06 '12 at 12:13
  • Do you mean `19 51 ...` and `20 47 ...`?? – Andreas Louv Jan 06 '12 at 12:13
  • Parse what into what? If you just want to split on a separator, there is a standard function for that, and you should look it up. – Marcin Jan 06 '12 at 12:14
  • Are you trying to convert a string of the top form into the bottom form? Could you describe a more general case? For example, what might happen if there were more than 2 spaces in a line? – Tom Elliott Jan 06 '12 at 12:18
  • possible duplicate of [How to use split?](http://stackoverflow.com/questions/2555794/how-to-use-split) – That1Guy Apr 22 '14 at 20:55

3 Answers3

35

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');
Rudolph Gottesheim
  • 1,671
  • 1
  • 17
  • 30
  • 3
    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. – Dzhuneyt Jan 31 '13 at 09:30
1

Like this:

var myString = "19 51 2.108997";
var stringParts = myString.split(" ");
var html = "<span>" + stringParts[0] + " " + stringParts[1] + "</span> <span>" + stringParts[2] + "</span";
user2316116
  • 6,726
  • 1
  • 21
  • 35
davidethell
  • 11,708
  • 6
  • 43
  • 63
0
var wrapper = $(document.body);

strings = [
    "19 51 2.108997",
    "20 47 2.1089"
];

$.each(strings, function(key, value) {
    var tmp = value.split(" ");
    $.each([
        tmp[0] + " " + tmp[1],
        tmp[2]
    ], function(key, value) {
        $("<span>" + value + "</span>").appendTo(wrapper);
    }); 
});
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123