Read numbers from <pre> - javascript

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.

The following will give you a 2-dimensional array:
var str = document.getElementsByTagName('pre')[0].textContent;
str // take the string and
.split('\n') // break it into an array of lines;
.map(function(line) { // then transform each line by
return line // taking the line,
.trim() // removing leading and trailing spaces,
.split(/\s+/) // and breaking it into an array at whitespace,
.map(Number); // with each piece cast to a number.
});

http://jsfiddle.net/Lwkw4ee4/
String.prototype.trim = function() { // just in case of an old browser
return this.replace(/^\s+|\s+$/gm,'');
}
var str = document.getElementById('data').innerHTML.trim();
var data = str.split(/\s+/);
alert(data);
data will be an 1D array of numbers (to be accurate - strings with numbers, but it does not matter - it is easy to cast).

http://jsbin.com/mepulu/2/edit
var text = document.getElementsByClassName('data')[0].innerHTML; // Text
var values = text.split(/\s+/); // Array of strings
var numbers = values.map(function(num) {
return parseInt(num, 10);
});
numbers; // Array of integers

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

Related

How to print out the even numbers in reverse order?

var num = prompt("Enter an integer : ");
var reversenum = num.reverse('');
document.write(reversenum);
I want to print out the even number of integers in reverse order after inputting an integer through the prompt, but I have no idea.
Even if I try to write split(), I don't think I can separate it because the letters are attached to each other. What should I do?
The result I want is,
Enter an integer : 8541236954
46248
Based on your updated question, I suppose what you want is to extract even-valued digits from a given integer, and display them in reverse order.
Since prompt() always returns a String, you can do one of the two ways to split it into digits and reverse their order:
Old-school JS way: num.split('').reverse()
ES6 array spread way: [...num].reverse()
Then, it is just a matter of using Array.prototype.filter() to return even numbers. Even numbers can be selected based on the criteria that their modulus of 2 is always 0 (i.e. when number is divided by 2, it has a remainder of 0).
Finally, join your filtered array so you get a string again.
See proof-of-concept order below:
const num = prompt("Enter an integer : "); // e.g. try '8541236954'
const digits = [...num].reverse();
const evenDigits = digits.filter(d => d % 2 ===0);
console.log(evenDigits.join('')); // e.g. '46248'
You need to first split the string into an array of characters, reverse the array and then join it again. I have given an easy to understand code which converts every character of the reversed string to an int and checks if that integer is even, followed by concatenating it in the answer.
var num = prompt("Enter an integer : ");
var reversenum = num.split('').reverse().join('');
var ans = "";
for (var i = 0; i < reversenum.length; i++)
{
var x = parseInt(reversenum[i]);
if(x%2 === 0)
ans = ans.concat(reversenum[i]);
}
console.log(ans);

Trim long number in JavaScript

For example, I got that long nubmer 1517778188788. How can i get first 6 digits from that number, like 151777 and trim another digits?
Just convert a number to string and then slice it and convert it back to Number.
const a = 1517778188788;
const str_a = a.toString();
const result = Number(str_a.slice(0, 6));
new String(your_number).substring(0,6)
(basically converting it to a string and substringing it). Don't forget to parse it back afterwards
Applicable only when you want to strip last 7 digits, and the numbers have constant length (13 in this case). Still leaving you with first 6 ones though.
const nr = 1517778188788;
const result = Math.floor(nr / 10000000)
Try this:
var num = 1517778188788; // long number
var str = num.toString(); //convert number to string
var result = str.substring(0,6) // cut six first character
result = parseInt(result); // convert it to a number
here is a working fiddle

Adding numbers within a string

I want to take a string of numbers and characters and add up the numbers.
For example: "In 2015, I want to know how much does iPhone 6+ cost?"
Output: 2021
Here is my current code:
var str = "In 2015, I want to know how much does iPhone 6+ cost?";
function sumFromString(str){
var punctuationless = str.replace(/['!"#$%&\\'()\*+,\-\.\/:;<=>?#\[\\\]\^_`{|}~']/g,"");
var finalString = punctuationless.replace(/\s{2,}/g," ");
var StringList = finalString.split(" ");
var sum = [];
for (i = 0; i < StringList.length; i++)
if (isInt(StringList[i])
sum.add(StringList[i]);
sum.reduce( (prev, curr) => prev + curr );
}
sumFromString(str);
My code takes a string and strips it of punctuation and then places each individual word/number into the array, StringList.
I can't get the next part to work.
What I tried was to iterate through each value in the array. The if statement is supposed to check if the array element is an integer. If so, it will add the integer to an empty array called sum. I then add all the values of the array, sum, together.
Much simpler:
function sumFromString(str) {
return (str.match(/\d+/g)||[]).reduce((p,c)=>+c+p);
}
Note in particular that I use +c+p - +c casting the current value from a string to a number, then adding it to p. This matches all the numbers in the string - getting an empty array if there were none - and reduces that.
For the sake of variety, here's a way to do it without regular expressions:
var myString = "5 bunnies ate 6 carrots in 2days.";
var myArray = myString.split('');
var total = 0;
for (var i = 0; i < myArray.length; i++) {
if (!isNaN(parseInt(myArray[i]))) {
total += parseInt(myArray[i]);
}
}
Fiddle Demo
note: If there's a chance myString could be null, you'd want to add a check before the split.
Split the string into an array of all characters with the split function and then run the filter function to get all numbers. Use the map function to go through all elements that include numbers, and delete characters from them that aren't digits.
Then use reduce to get the sum of all numbers. Since we're dealing with strings here, we have to perform type conversion to turn them into numbers.
string.split(' ').filter(function(word) {
return /\d+/.test(word) }
}).map(function(s) {
return s.replace(/\D/, '')
}).reduce(function(a,b) {
return Number(a) + Number(b);
});

How to extract last characters of type number javascript/jquery

I have some strings like:
row_row1_1,
row_row1_2,
row_row1_13,
row_row1_287,
...
and I want to take the last numbers of that strings, ut can be 1, 2, 13 or 287. That strings are generated automatically and I can't control if there is going to be 1 number, 2 numbers, 3 numbers...
I would like to make a function that takes the last number character, or the numbers after the second '_' character. is there any idea?
Thank you very much!
If your strings always follow this pattern str_str_str then you can use the split method and get the 2ยบ index of the array, like this:
var number = str.split('_')[2];
As #PaulS said, you can always use regex for that purpose:
var getLastNumbers = function(str)
{
return str.replace(/.+(_)/, '');
};
getLastNumbers("row_row1_287"); // Will result -> 287
Fiddle
Taking the last numeric characters
function getNumericSuffix(myString) {
var reversedString = myString.split('').reverse().join('');
var i, result="";
for(i = 0; i < reversedString.length; i++) {
if(!isNaN(reversedString[i])) {
result = reversedString[i] + result;
} else break;
}
return parseInt(result); // assuming all number are integers
}

How do I split a string with multiple commas and colons in javascript? [duplicate]

This question already has answers here:
How do I split a string with multiple separators in JavaScript?
(25 answers)
Closed 8 years ago.
How do I split a string with multiple separators in JavaScript? I'm trying to split on both commas and : colon but, js's split function only supports one separator.
Example :
materialA:125,materialB:150,materialC:175
I want to split both these values into array like
materiaA,materialB,materialC
and second
125,150,175
Or anybody can give me idea how could I multiply these numbers with a constant to get like
materialA:1250, materialB:1500,materialC:1750.
You can split with more than one seperator if you're using regex:
.split(/:|,/)
This would give
["materialA", "125", "materialB", "150", "materialC", "175"]
Changing the approach completely, if all you want to do is multiply all the numbers in your string by a fixed coefficient, you can use string.replace:
var string = "materialA:125,materialB:150,materialC:175";
var coef = 10;
var result = string.replace(/\d+/g, function(match){
return parseInt(match)*coef;
});
Then print(result) outputs the string
materialA:1250,materialB:1500,materialC:1750
\d is a shortcut for [0-9].
Example using #mitim's method:
var str = 'materialA:125,materialB:150,materialC:175',
multiplier = 2;
str = str.split(',').map(function (elem) {
var parts = elem.split(':');
parts[1] *= multiplier;
return parts.join(':');
}).join(',');
This will give you:
materialA:250,materialB:300,materialC:350
You could split the string by comma first, then loop through the resulting array. In that array, each entry would be something like "materialA:125". From there, you can split by the colon and append each part to its own list to work with or if you prefer, just multiply the second half (cast to int first) and rejoin it in to your original string.
Even though someone gave a much better answer, here's a bit of code that does what I mentioned above (since you asked)
var inputString = "materialA:125,materialB:150,materialC:175";
var mats = new Array();
var numbers = new Array();
var temp;
var elements = inputString.split(",");
for(var element in elements){
temp = elements[element].split(":");
mats.push(temp[0]);
numbers.push(parseInt(temp[1]));
}
console.log(mats); // prints ["materialA", "materialB", "materialC"]
console.log(numbers); // prints [125, 150, 175]
You could simply use following Regex:
/[:,]/
And following string method:
mystring = 'materialA:125,materialB:150,materialC:175';
result = mystring.split(/[:,]/);
Here is a Fiddle.

Categories

Resources