How to use isNAN and separator issues [duplicate] - javascript

This question already has answers here:
How to remove comma from number which comes dynamically in .tpl file
(7 answers)
How can I parse a string with a comma thousand separator to a number?
(17 answers)
Closed 5 years ago.
I need to find a way of either inputting separator eg, 12,000 without getting NaN message and if this can't be done then showing a message instead. I have looked through various sites and StackOverflow and can't work out how to do this (newbeeee issue). Current code as follows:
<script language="JavaScript" type="text/javascript">
function calcsavings()
{
var B1=document.forms[0].B1.value;
var B2n = Number("1516");
var B2=+B2n + +B1;
var B4 = Number("0.138");
var t;
for (i=0; i<document.forms[0].ITR.options.length; i++)
{
if (document.forms[0].ITR.options[i].selected)
t = document.forms[0].ITR.options[i].value;
}
var result=(B1/t-(B2/(1+B4)))*t
result=Math.round(result);
document.getElementById("childcaresavings").innerHTML=result;
}
</script>
I have stripped out the non-working code I tried before posting.

Is there anything wrong with adding a NaN check for result?
result=Math.round(result);
var htmlContent = Number.isNaN(result) ? "not a valid number" : result;
document.getElementById("childcaresavings").innerHTML=htmlContent ;
edit: If you're looking for a casual use of parsing. You can just use a global replace that will remove anything except numbers and periods.
if (document.forms[0].ITR.options[i].selected) {
var inputVal = document.forms[0].ITR.options[i].value;
var removedCommas = inputVal.replace(/[,]/g, "")
if (removedCommas[0] === "£") {
removedCommas = removedCommas.slice(1, removedCommas.length)
}
t = removedCommas
}
What this does: It takes your input and removes all commas and £ if it is the first character in the input. Assuming your user enters a sane entry, it will process the number as expected. If your use enters anything weird like / * & #, etc, NaN will be returned and your error will show.

Related

How can i remove zero from input number in form javascript? [duplicate]

This question already has answers here:
Input field value - remove leading zeros
(8 answers)
Closed 1 year ago.
I have this code and I want to remove first zero from phone number.
mobile = $('#country_code').val();
mobile += input.val();
Country code is: 966
Phone input is: 055642444
And output in this code is: 966055642444
I want it to be 96655642444 without zero after country code.
Thanks
You can use substring to remove the first N characters from a string.
First of all, assign a variable with the value of input.val()
let str = input.val()
Now, you can index the Nth element of str and check its value:
if (str[0] === "0") str = str.substring(1)
With this, you have successfully checked if the first character is "0" and reassigned the str variable accordingly.
Have you tried parseInt(), integers don't have leading 0s - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
mobile = $('#country_code').val();
mobile += parseInt(input.val());
For this, I'd use substring which returns a new string. Example :
mobile = '0652447766';
mobile = mobile.substring(1)
console.log('mobile = ', mobile)
>> mobile = '652447766'
Warning ! Calling mobile.substring() doesn't actually modify mobile ! Strings are immutable in Js, so you'll have to get the returned value of substring() with mobile = mobile.substring(1)
Hope it helped !
If you store the value of the phone number in the html element <input> as a string - like this:
<input type='text' />
Then just use the native javascript parseInt() method to remove the leading zero, which removes the leading zero.
Like this:
const withoutZero = parseInt(input.val());
Or you can leave the value as a string, and if the string starts with "0", you can also delete it as follows:
const withoutZero = input.val().replace(/^0+/, '');

What is the easier way to convert single string word without spaces into Title case within less code? [duplicate]

This question already has answers here:
How to capitalize first letter and lowercase the rest of the string
(8 answers)
Closed 2 years ago.
I have single string and I want to convert this to title case.
JS is not providing built in function.
var difficulty = "easy"; // medium, hard
difficulty[0].toUpperCase();
document.write(difficulty) // It is printing in small.
If you don't want to repeat the code multiple times, you can add a method to the String prototype, that would allow you to easily reuse the functionality many times
String.prototype.titleCase = function () {
var sentence = this.toLowerCase().split(" ");
for(var i = 0; i< sentence.length; i++){
sentence[i] = sentence[i][0].toUpperCase() + sentence[i].slice(1);
}
return sentence.join(" ");
}
var difficulty = "easy";
document.write(difficulty.titleCase());
document.write("<br/>")
document.write("medium".titleCase());
document.write("<br/>")
document.write("hard".titleCase());
This will also work on words with spaces, so very easy // would give "Very Easy"

Convert html decoded string to human readable string in nashorn [duplicate]

This question already has answers here:
HTML Entity Decode [duplicate]
(17 answers)
Unescape HTML entities in JavaScript?
(33 answers)
Closed 2 years ago.
I have some strings like this(encoded as utf-8):
توسعه.
I want to convert them to:
توسعه
How can I do that in javascript?
The solution needs to be compatible with nashorn, since I am running the code in a virtual engine in java.
NOTE: None of these HTML Entity Decode, Unescape HTML entities in Javascript? are acceptable for my question, since they do not work in nashorn.
P.S: I have searched for possible solutions, and it was suggested by many to use decodeURIComponent(escape(window.atob(yourString))) (with slight differences), which apparently does not work, as I have tried them in vscode(javascript).
Unclear if nashorn supports DOM methods, but typically you can do
var x = 'توسعه'
var y = document.createElement("div")
y.innerHTML = x;
console.log(y.textContent)
The string I mentioned in the question can be broke down to smaller parts separated by ;. Each part, is a combination of &# and a hex number(e.gx62A) corresponding to a character(ت).
Following code will do the job, by parsing input str and finding corresponding characters. The result is concatenation of characters.
human_readable = function (str) {
hex_code = str.match(/([^&#]+[\w][^;])|(\s)/g)
s = ''
for (j = 0; j < hex_code.length; j++) {
if (hex_code[j] != ' ') {
int_code = parseInt("0" + hex_code[j])
char = String.fromCharCode(int_code)
} else {
char = ' '
}
s = s + char
}
return s
}
console.log(human_readable('توسعه'))
P.S: I have assumed that if str contains white spaces, it will be simply ' ', and not the corresponding unicode.

Javascript: Getting last few characters of a string [duplicate]

This question already has answers here:
How can I get last characters of a string
(25 answers)
Closed 5 years ago.
This is a trivial problem if we are storing string in a variable. But out of curiosity, I need to understand how to achieve this without storing string in variable?
// To get first few characters of a string, we can do something like this:
var x = "amangupta".substring(0,7); //amangup
// How to get last 7 characters
var x = "amangupta".substring(this.length - 7, this.length); // does not work, looking for similar approach
var str = "amangupta";
var x = str.substring(str.length - 7, str.length); // will work fine
How to get last 7 characters
Try
"amangupta".slice(-7)
Without an extra variable you need to use the string again
"amangupta".substring("amangupta".length - 7, "amangupta".length);

Variables and math operators [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Strange javascript addition problem
I know there's obviously a solution for this, and I've done it before, but I can't remember it and now I can't find it.
​<div>1</div>​​​​​​​​
$(function() {
var number = $('div').text();
var math = number + 2;
$('body').text(math);
});​
http://jsfiddle.net/G5zdx/
number is not being treated as an integer so math's value is "12" instead of "3". How can I correct this?
There are many ways, but
var math = (1 * number) + 2;
is a simple one. Whether you should be detecting possible ill-formed non-numbers depends on the nature of the rest of your code.
The parseInt() function is useful, but it probably should be called with 10 as its second argument to avoid interpreting numbers that begin with zero as octal constants instead of decimal. Also, parseInt() will not treat a string like "23skidoo" as an error, which may or may not be OK in your application.
​<div>1</div>​​​​​​​​
$(function(){
var number = parseInt($('div').text(), 10);
var math = number+2;
$('body').text(math);
});​
You can parse a string as an int using parseInt(string[, radix]).
Your code would look as follows
$(function(){
var number = $('div').text();
var math = parseInt(number, 10)+2;
$('body').text(math);
});
Source: http://www.javascripter.net/faq/convert2.htm

Categories

Resources