Javascript: Convert numbers inside the string - javascript

Im working on a simple conversation form, where I need to input dimensions ex. 12x24x36 inches to 304.8 x 609.6 x 914.4 mm.
My problem is I don't know how to compute convert those numbers separately.
I manage to remove the x but all the numbers merge.
Thanks, I hope you understand me.
here is my sample code
HTML
<h4>Dimensions</h4>
<label>inches <input id="number1"></label>
<label>mm <input id="number2"></label>
<button type="button" onclick="myFunction()">convert</button>
JS
function myFunction() {
var inches = document.getElementById("number1").value;
var removex = inches.replace(/x/g,"");
var input = parseInt(removex);
document.getElementById("number2").value = input
}
CODEPEN
https://codepen.io/anon/pen/yPpmej

If you have a string like:
var str = '304.8 x 609.6 x 914.4 mm'
You can use split() and parseFloat() to get an array of numbers with:
var str = '304.8 x 609.6 x 914.4 mm'
var numbers = str.split('x').map(parseFloat)
console.log(numbers)
You just need to know your input format so you can adjust for other variations.
parseFloat() will ignore any non-numeric characters after the numbers so it works well for stripping units.

If your receiving "12x24x36" as input(string) then for complete desired result update your function as below:-
function myFunction() {
var inches = document.getElementById("number1").value;
var inchesArr = inches.split("x");
var mmArr = inchesArr.map(function(i) {
return parseFloat(i) * 25.4;
});
var mmString = mmArr.join("x");
document.getElementById("number2").value = mmString;
}

EXPLANATION
You can convert your input example 12x24x36 into an array via str.split('x'), then do the math conversion from inch to millimeters (x inches * 25.4) and push those back into a new array of millimeters values. Then you can rejoin those values with an x via str.join('x') and put them back into your document. Here's what it looks like.
SCRIPT
function myFunction() {
var inches = document.getElementById("number1").value.split('x');
var millimeters = [];
for (var i = 0; i < inches.length; i++) millimeters.push(parseInt(inches[i]*25.4));
document.getElementById("number2").value = millimeters.join('x');
}
CODEPEN
https://codepen.io/anon/pen/KyZOYb

Related

Replacing numbers in a string with a modified number using regex - Javascript

I'm new to javascript so apologies if I've missed something simple. I'm working on a script to take a string from one cell in Sheets, add VAT at 5% to any applicable numbers and output the amended string in a new cell. I'm happy with the regex capturing the numbers I need, but getting the amended string correct is proving tricky.
So far the script looks like this:
function strReplace() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var str = sheet.getRange(4,2).getValue(); // A cell with a string like this: "ID: 10101010101010 | Price 1: £4.54 | Price 2: £2.87"
var regex = /\d{1,8}(?:\.\d{1,8})/g // Regex to ignore numbers greater than 8 digits, including decimals
var newStr = str.match(regex);
for (var x = 0; x < newStr.length; x++) {
var newRates = newStr[x]*1.05;
var output = str.replace(newStr, newRates)
sheet.getRange(4,3).setValue(output);
}
}
I've tried a bunch of variations but with no success. I feel there is an easier way to achieve what I'm looking for from what I already have. Any recommendations would be much appreciated.
Thanks!
To do this kind of thing, you use the function callback version of replace:
var str = "ID: 10101010101010 | Price 1: £4.54 | Price 2: £2.87";
var regex = /\d{1,8}(?:\.\d{1,8})/g; // Regex to ignore numbers greater than 8 digits, including decimals
var output = str.replace(regex, function(match) {
return 1.05 * match;
});
console.log(output);
You might choose to use parseFloat(match) rather than just using match, which relies on * coercing the string to number.
And you might consider .toFixed(2) on the result to round and format to two places (depending on whether you want to round the way it rounds). For instance:
var str = "ID: 10101010101010 | Price 1: £4.54 | Price 2: £2.87";
var regex = /\d{1,8}(?:\.\d{1,8})/g; // Regex to ignore numbers greater than 8 digits, including decimals
var output = str.replace(regex, function(match) {
return (1.05 * match).toFixed(2);
});
console.log(output);
basically your solution is very close, you just needed tot assign the str.replace, use the newStr[x] and also wait to end the for to assign it into the cell.
check the sample below.
function strReplace() {
let str = "ID: 10101010101010 | Price 1: £4.54 | Price 2: £2.87";
var regex = /\d{1,8}(?:\.\d{1,8})/g
var newStr = str.match(regex);
for (var x = 0; x < newStr.length; x++) {
var newRates = parseFloat(newStr[x]) * 1.05;
str = str.replace(newStr[x], newRates)
}
return str;
}
var replaced = strReplace();
console.log(replaced)

How to get remaining string after substring deletion in JavaScript?

I have a string 123456789.
My aim is to get 1236789 after deleting 45.
I used slice method to delete the string 45.
var x = 123456789;
res = x.slice(4, 5); //my output is 45
I need the output to be 1236789
Any help would be appreciated.
Slice before, slice after, and concatenate the resulting strings or replace the 45 with an empty string:
var x = "123456789"
var res1 = x.slice(0, 3) + x.slice(5)
console.log(res1)
var res2 = x.replace('45', '')
console.log(res2)
try replace/2.
"123456789".replace("45", "") /** 1236789 */
Or, if your input is an integer and you need and integer as an outcome,
var a = 123456789;
parseInt(a.toString().replace("45", ""))
You can so this:
var x = "123456789";
var result = x.substr(0, 3) + x.substr(5);
console.log(result)

Replace character of a string with the character from an array

I'm trying to make a script that changes text into these cool looking letters, it looks like everything should be working but when I try to send the replaced message it gives me a character like a white question mark on a black background. This: �
Here's the code:
var mm = "test";
var alphabet = "🇦🇧🇨🇩🇪🇫🇬🇭🇮🇯🇰🇱🇲🇳🇴🇵🇶🇷🇸🇹🇺🇻🇼🇽🇾🇿";
var nalphabet = "abcdefghijklmnopqrstuvwxyz";
for(var z in mm){
var x = nalphabet.indexOf(mm[z].toLowerCase());
var ool = alphabet[x];
msg.channel.sendMessage(ool);
}
This is all about the coding of characters. Each of your cool-looking letters has length 2. So when you try to get such character directly by index, you receive just a half of it. As a solution you can try to join two sibling characters. Something like this
var mm = "test";
var alphabet = "🇦🇧🇨🇩🇪🇫🇬🇭🇮🇯🇰🇱🇲🇳🇴🇵🇶🇷🇸🇹🇺🇻🇼🇽🇾🇿";
var nalphabet = "abcdefghijklmnopqrstuvwxyz";
for(var z in mm){
var x = nalphabet.indexOf(mm[z].toLowerCase());
var ool = alphabet[x * 2] + alphabet[x * 2 + 1];
msg.channel.sendMessage(ool);
}
Try this one:
var message = "test";
var alphabet = ["🇦","🇧","🇨","🇩","🇪",
"🇫","🇬","🇭","🇮","🇯",
"🇰","🇱","🇲","🇳","🇴",
"🇵","🇶","🇷","🇸","🇹",
"🇺","🇻","🇼","🇽","🇾","🇿"];
var nalphabet = "abcdefghijklmnopqrstuvwxyz";
for(var letter in message) {
var x = nalphabet.indexOf(message[letter].toLowerCase());
var ool = alphabet[x];
document.write(ool);
}
Here is a Fiddle.

Get id as a number in javascript..?

A simple question..
var x = document.getElementById('xNum');
var y = document.getElementById('xNum');
var result = x * y;
document.write(result);
and
<div id="xNum">20</div>
<div id="yNum">50</div>
It displays 20 and 50. why not calculating 20 * 50? Why does it get as a integer or how can I get numbers in an div?
Thanx!
I don't get any result with that:
var x = document.getElementById('xNum').innerHTML;
var y = document.getElementById('xNum').innerHTML;
var result = parseInt(x) * parseInt(y);
document.write(result);
Use parseInt and process it on their HTML,
var result = parseInt(x.innerHTML) * parseInt(y.innerHTML)
If you don't need to support browsers priot to IE9, you should use textContent instead of innerHTML.
If your numbers might be floats you should check out parseFloat instead
If you need to be able to handle numbers like 012 you should specify the radix parameter as they might be interpreted the wrong way by parseInt.
In this case you should use parseInt(x.innerHTML,10)
it should be
var x = document.getElementById('xNum').innerHTML;
var y = document.getElementById('yNum').innerHTML;
var result = x * y;
document.write(result);
Parse them into integers:
var x = document.getElementById('xNum');
var y = document.getElementById('yNum');
var result = parseInt(x.innerHTML, 10) * parseInt(y.innerHTML, 10);
The value you are getting is a string, so in order to use it as a number you should cast it to the integer (or float):
var x = +document.getElementById('xNum').innerHTML;
var y = +document.getElementById('xNum').innerHTML;
var result = x * y;
I used unary + operator, there are another methods like parseInt, Number constructor, etc.
By now the possible ways would have been exhausted, but here's an example with textContent:
var x = document.getElementById('xNum'),
y = document.getElementById('yNum'),
toIntNum = function(element) {
return parseInt(element.textContent || element.innerText || 0, 10);
},
result;
result = toIntNum(x) * toIntNum(y);
Demo
Js:
var x = document.getByElementId('xNum').innerHTML;
var y = document.getByElementId('xNum').innerHTML;
var result = parseInt(x) * parseInt(y);
document.write(result);
you must cast as int so calculation done. By default the value consider as string .
var x = document.getByElementId('xNum');
var y = document.getByElementId('xNum');
var result = parseInt(x) * parseInt(y); //use parseInt or parseDouble
document.write(result);
and
<div id="xNum">20</div>
<div id="yNum">50</div>
it give 1000
You have to use parseInt() function in javascript for parsing a string to return an integer.
Your code should be like this :
var x = document.getElementById('xNum');
var y = document.getElementById('yNum');
var result = parseInt(x.innerHTML) * parseInt(y.innerHTML);
document.write(result);

Sum of a string of one-digit numbers in javascript?

I'm trying to write a script that adds the left side of a string and validates it against the right side.
For example:
var left = "12345"
var right = "34567"
I need to do some sort of sum function that adds 1+2+3+4+5 and checks if it equals 3+4+5+6+7.
I just don't have a clue how to do it.
I think I need to use a for loop to iterate through the numbers such as
for (var i = 0, length = left.length; i < length; i++)
But I'm not sure how to add each number from there.
EDIT the var is actually being pulled in from a field. so var left = document.blah.blah
DEMO
var left = "12345"
var right = "12345"
function add(string) {
string = string.split(''); //split into individual characters
var sum = 0; //have a storage ready
for (var i = 0; i < string.length; i++) { //iterate through
sum += parseInt(string[i],10); //convert from string to int
}
return sum; //return when done
}
alert(add(left) === add(right));​
Find the length of the string
then in a temp Variable store the value pow(10,length-1)
if you apply module function (left%temp) you will ge the Last significant digit
you can use this digit to add
repeat the process till the length of the string left is 0
6 Repeat all the steps above for the right as well and then compare the values
Note: convert the string to int using parseInt function
var sum = function(a,b){return a+b}
function stringSum(s) {
var int = function(x){return parseInt(x,10)}
return s.split('').map(int).reduce(sum);
}
stringSum(a) == stringSum(b)

Categories