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>
5
  • 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? Commented Jan 6, 2012 at 12:13
  • Do you mean <span>19 51</span> <span>...</span> and <span>20 47</span> <span>...</span>?? Commented Jan 6, 2012 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. Commented Jan 6, 2012 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? Commented Jan 6, 2012 at 12:18
  • possible duplicate of How to use split? Commented Apr 22, 2014 at 20:55

3 Answers 3

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');
Sign up to request clarification or add additional context in comments.

1 Comment

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

Comments

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);
    }); 
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.