Adding numbers within a string - javascript

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

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

issue with substring indexing

Instructions for this kata:
In this Kata, we will check if a string contains consecutive letters as they appear in the English alphabet and if each letter occurs only once.
It seems that my code is indexing the strings differently per function call on this one. for example, on the first test "abcd", the starting index is shown as 0, which is correct, and on the second example, "himjlk", the
var subString = alphabet.substring(startIndex, length);
returns "g", instead of "h"
troubleshooting this section
var length = orderedString.length;
//startChar for string comparison
var startChar = orderedString.charAt(0);
//find index in aphabet of first character in orderedString.
var startIndex = alphabet.indexOf(startChar);
//create substring of alphabet with start index of orderedString and //orderedString.length
var subString = alphabet.substring(startIndex, length);
function solve(s) {
//alphabet string to check against
const alphabet = `abcdefghijklmnopqrstuvwxyz`;
//check s against alphabet
//empty array to order input string
var ordered = [];
//iterate through alphabet, checking against s
//and reorder input string to be alphabetized
for (var z in alphabet) {
var charToCheck = alphabet[z];
for (var i in s) {
if (charToCheck === s[i]) {
ordered.push(s[i]);
}
//break out of loop if lengths are the same
if (ordered.length === s.length) {
break;
}
}
if (ordered.length === s.length) {
break;
}
}
//join array back into string
var orderedString = ordered.join(``);
//length for future alphabet substring for comparison
var length = orderedString.length;
//startChar for string comparison
var startChar = orderedString.charAt(0);
//find index in aphabet of first character in orderedString.
var startIndex = alphabet.indexOf(startChar);
//create substring of alphabet with start index of orderedString and orderedString.length
var subString = alphabet.substring(startIndex, length);
//return if the two are a match
return subString == orderedString ? true : false;
}
console.log(solve("abdc")); //expected `true`
console.log(solve("himjlk")); // expected `true`
console.log(solve("abdc")); should provide the substring "abcd" and return true, which it does.
console.log(solve("himjlk")); should put together "hijklm" and return true, but instead gives me g based on index 6 of alphabet, not sure why it's doing this, should be index 7 "h" returns false based upon this error.
The problem is that you're using substring() instead of substr(). Though that might sound similar there's a difference.
With substring the second parameter doesn't determine the length as you might have expected. It's actually the index to stop.
That your function works as expected with the string abcd is pure coincidence since in this case the length from index 0 and the end index are the same.
function solve(s){
const alphabet = `abcdefghijklmnopqrstuvwxyz`;
var ordered = [];
for(var z in alphabet){
var charToCheck = alphabet[z];
for(var i in s){
if(charToCheck === s[i]){
ordered.push(s[i]);
}
if(ordered.length === s.length){ break; }
}
if(ordered.length === s.length){ break; }
}
var orderedString = ordered.join(``);
var length = orderedString.length;
var startChar = orderedString.charAt(0);
var startIndex = alphabet.indexOf(startChar);
var subString = alphabet.substr(startIndex, length);
return subString == orderedString ? true: false;
}
console.log(solve("himjlk"));
You approach is also correct. I am giving another solution using sort() and charCodeAt. Instead of getting the index and then breaking string into parts to compare just use includes()
function check(str){
let org = [...Array(26)].map((x,i) => String.fromCharCode(i + 97)).join('');
str = str.split('').sort((a, b) => a.charCodeAt(0) - b.charCodeAt(0)).join('');
return org.includes(str);
}
console.log(check("abdc"))//true
console.log(check("himjlk"));//true
console.log(check("himjlkp"));//false
Explanation:
Frist Line:
let org = [...Array(26)].map((x,i) => String.fromCharCode(i + 97)).join('');
is use to create string "abcd....xyz".
[...Array(26)] will create an array of 26(no of alphabets) undefined values.
map() is a function which takes a callback and the create an array based the values of previous. The first parameter of map() callback x is the value itself which will be undefined(because all the values in array are undefined).
i the second parameter will be the index of the element. Which will start from 0 upto 25.
String.fromCharCode is function which takes a character code(integer) and then convert it to string. For example character code for a is 97 so String.fromCharCode(97) will return "a". 98 for "b", 99 for "c" etc.
So after map() an array like ["a","b"....,"z"] will be generated.
-join() will convert that to string
Second Line:
str is given string. str.split('') will convert string to array. For example
if str is "abdc" it will return ["a","b","d","c"]
sort() is the array method which takes the callback. The two parameters are two values to be compared during sort(). a and b are two values.
charCodeAt acts in reverse as String.fromCharCode. For example "a".charCodeAt(0) will be return 97 for "b" it will 98 and so on.
a.charCodeAt(0) - b.charCodeAt(0) which is returned from sort() will sort array is ascending order. And join() will convert array to string.
So string "abdc" will become "abcd"
Third Line:
The third line is the main one. org is string "abcdefghijklmnopqrstuvwxyz". Now if any string is a substring of this string then it means its in alphabetical order. So we check the sorted str is includes in the string or not.
You can clean up the second line by
str = str.split('').sort().join('');
Because if no callback is passed to sort() it will sort in default order. Mean alphabetical order.

Why does 'duplicates' property keeps returning 3 instead of 2?

The task I am undertaking is as follows:
The function should be called removeDuplicates and should return an object literal containing a 'uniques' property, which should be the sorted input string but without any duplicates or special characters.
The returned object should also have a 'duplicates' property which should represent the total number of duplicate characters dropped.
So:
removeDuplicates('th#elex_ash?')
should return:
{uniques: 'aehlstx', duplicates: 2}
Here is my code:
function removeDuplicates(str) {
var stg = str.split("");
var nstr = [];
var allowed = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
var count = 0;
for(var i = 0; i<stg.length;i++){
if(nstr.indexOf(stg[i])== -1){
if(allowed.indexOf(stg[i]) > -1){
nstr.push(str[i])
}
else{
count +=1;
}
}
}
return{uniques: nstr.sort().join(""),duplicates: count}
}
But the result returns {uniques: 'aehlstx', duplicates: 3} instead.
You are checking first if you've seen the character before, and THEN checking it was an allowed character and counting the number of times you see a non-allowed character.
You need to check if the character is allowed, and then see if you've seen it before.
Because you are counting the not allowed characters :)

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
}

New to javascript, how to write reverse iteration?

I'm currently taking an introduction CIS class at my university and one of the projects is javascript. It is split into two unrelated parts and I was able to do the second part but I'm stuck on the first one. My professor wants me to write an iteration that will display in a reverse order whatever name I write in the prompt screen. So if I write "John Smith" it will display "htims nhoj". The issue is that I have no idea how to write it.
<html>
<body>
<script>
var namIn = window.prompt("Enter name:" );
var namAr = namIn.split("");
var namArLen = namAr.length;
document.write(namAr + "<br /> Length: " + namArLen);
</script>
</body>
</html>
Strings in JavaScript have a function called split() which turn them in to Arrays. Arrays in JavaScript have a function called reverse() which reverse their order, and a function called join() which turn them back into Strings. You can combine these into:
"John Smith".split("").reverse().join("")
This returns:
"htimS nhoJ"
Also, and I don't know if this is a typo, but you can throw a toLowerCase() to get 100% of what your question is after:
"John Smith".split("").reverse().join("").toLowerCase()
returns:
"htims nhoj"
As for the question in your title, you can specify the direction of a for loop in the last argument like so:
var reversed = [];
var name = "John Smith".split("");
for(var i = name.length-1; i >= 0; i--) {
reversed.push(name[i]);
}
console.log(reversed.join(""));
Which will output:
"htimS nhoJ"
There's no need to split this string into an array. Just use the charAt() function and a simple for loop.
var name = window.prompt("Enter name:");
var reverse = "";
for (var i = name.length - 1; i >=0; i--) {
reverse += name.charAt(i);
}
console.log(reverse)
Instead of converting the string to an array first, you're just reading the characters out of the string directly.
You can accomplish this by iterating only half the number of characters.
DEMO: http://jsfiddle.net/vgG2P/
CODE:
var name = "Bob Dylan".split("");
// The counters will meet in the middle.
// --------------+----------------------
// first char last char | inc dec
// -------v-------------v-----------v----v----v
for(var i = 0, j = name.length-1; i < j; i++, j--) {
var temp = name[i]; // Store the `i` char
name[i] = name[j]; // Replace the `i` char with the `j` char
name[j] = temp; // Replace the `j` char with the `i` char we stored
}
console.log(name.join("")); "nalyD boB"
EXPLANATION:
What we did was split the characters into an Array, and maintain two counters, one that increments from the first character at 0, and the other that decrements from the last character at .length - 1. Then simply swap the characters.
The iteration continues while your incrementing counter is less than your decrementing counter. Since they will meet in the middle, you'll end up incrementing only half the total length.
We can also build the halves of the result without using an Array:
DEMO: http://jsfiddle.net/vgG2P/1/
var name = "Bob Dylan";
var start = "", end = ""
for(var i = 0, j = name.length-1; i < j; i++, j--) {
end = name.charAt(i) + end
start += name.charAt(j)
}
if (i === j)
start += name.charAt(i)
console.log(start + end); "nalyD boB"
I'm assuming that your professor would not be asking you how to reverse a string if he hasn't yet introduced you to the concept of arrays and loops. Basically, a string like John Smith is just an array of characters like this:
0123456789
John Smith
Again, thinking in the sense that a string is just an array of characters, you have have 10 characters that need to be reversed. So how do you go about doing this? Well, you basically need to take the last character h from the "array" you're given and make it the first character in a new "array" you're going to create. Here's an example:
var known = 'John Smith';
var reversed = ''; // I'm making an empty string aka character array
var last = known.length - 1 // This is the index of the last character
for (var i = 0; i < known.length; i++)
{
temp += known[last - i];
}
(You can see it working here)
So what's happening?
We're looping over known starting at 0 and ending at 9 (from the first character to the last)
During each iteration, i is incrementing from 0 - 9
last always has a value of 9
last - i will give us indexes in reverse order (9, 8, 7, ..., 0)
So, when i is 0, last - i is 9 and known[9] is "h"; repeat this process and you get the reversed string
Hopefully this helps explain a little better what's happening when you call reverse() on an array.
(1) A more straight forward way without built-in functions:
function reverse(str) {
let reversed_string = "";
for (let i = str.length - 1; i >= 0; i--) {
reversed_string += str[i];
}
return reversed_string;
}
(2) Using ES2015 'for' helper function:
function reverse(str) {
let reversed_string = "";
for (let character of str) {
reversed_string = character + reversed_string;
}
return reversed_string;
}
(3) Using ES6 syntax and ES5.1 reduce():
function reverse(str) {
return str.split('').reduce((reversed, char) => char + reversed, '');
}
// reduce takes in 2 arguments. (1) arrow function, and (2) empty string.
Chances are, for an interview, that you will not able to use the built-in functions, especially for "reverse()".

Categories

Resources