Search code examples
javascripthtmlpre

Read numbers from <pre>


I am trying to calculate certain numbers in an array of numbers in a pre tag. Such as count how many of the numbers are 7 or higher. For example, I have this

    <pre class="data">2 7 3 1 2
    6   6   2   5   3
    8   2   5   9   9
    5   10  5   6   10
    2   10  3   </pre>

I've figured out how to get to the numbers in a general way:

    document.getElementsByTagName ('PRE')[0].firstChild.data = document.getElementsByTagName ('PRE')[0].firstChild.data.replace (/\t+$/, '')

But I do not know how to get at the individual numbers. Is it an array? Or a list of numbers that I need to parse by space?

I've looked at this thread: Using <pre> tag to display data in columns? and tried to use a for loop grabbing $entry[i], but I am not able to read individual numbers.


Solution

  • The content of the pre tag is just text. In order to access the numbers, you have to parse the text. I'm assuming you just need the list of numbers, and there is no significance to the columns.

    If this is true, what you need to do is split the text on whitespace, and then process each item:

    var number_string = document.getElementsByTagName ('PRE')[0].firstChild.data;
    
    var numbers = number_string.split(/[\s]+/);
    var a_number;
    
    for (var i = 0; i <= numbers.length; i++) {
        a_number = parseInt(numbers[i]);  // assuming the numbers are whole numbers.
    }
    

    Note that numbers[i] is actually a string representation of the number, so you need to use parseInt(numbers[i]) to get the real number. (or parseFloat(numbers[i]) if they are not whole numbers)

    Hope that's helpful.

    Jay