How to remove $ from javascript variable? [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Remove characters from a string
I have a variable p which I would like to remove the $ from. This variable will be a number such as $10.56. How can I do this? I thought it could be done using .replace('$','') but i'm not quite sure how to implement this.
Here is my javascript code:
function myFunction() {
var p = parseFloat(document.getElementById('p_input').value);
var q = parseFloat(document.getElementById('q_input').value);
if (!q){
document.getElementById('t').value = '';
}
else {
var t = q * p;
document.getElementById('t_output').value = t;
}
}

It's pretty simple:
var myString = "$15.62"
console.log(myString.replace('$', ''));
//Logs: "15.62"
Please note that this new value is not actually "saved" to myString, you'll have to assign it to a variable, yourself:
var newString = myString.replace('$', '');

Try this, assuming that the values of p_input and q_input will be the money values:
var p = parseFloat(document.getElementById('p_input').value.replace('$', ''));
var q = parseFloat(document.getElementById('q_input').value.replace('$', ''));

Related

Javascript wrong math [duplicate]

This question already has answers here:
Adding two numbers concatenates them instead of calculating the sum
(24 answers)
Closed 6 years ago.
I'm not sure what's wrong.
There are two variables, cena and uhrada. cena = 10 and uhrada = 279.8. I want to add them but I am getting 279.810 instead of 289.8.
Thanks for any help!
function priplatok(vstup1, vstup2) {
var chid = vstup1;
var cena = vstup2;
var uhrada = document.getElementById('uhr').value;
if (document.getElementById(chid).checked) {
var pridatu = uhrada + cena;
alert(pridatu);
}
}
The reason is that the values you take from the HTML input elements are always strings, even when they look like numbers. You have to first convert them, for instance with parseInt(...) or parseFloat():
var pridatu = parseFloat(uhrada) + parseFloat(cena);
A shorter way is to force conversion with a +:
var pridatu = +uhrada + +cena;
Although this is concise, you should probably first check if the input really is numeric. I refer to a popular question "Validate decimal numbers in JavaScript - IsNumeric()".
You get a string from document.getElementById('uhr').value.
If you want to do math, you need to cast the value either with parseInt(string, 10) or with parseFloat(string) to a number, implicit with a unary plus.
Your code:
function priplatok(vstup1, vstup2) {
var chid = vstup1;
var cena = vstup2;
var uhrada = +document.getElementById('uhr').value; // use implicit cast to number
if (document.getElementById(chid).checked) {
var pridatu = uhrada + cena;
alert(pridatu);
}
}
Thats because the values are strings and not numbers.
You have to make them numbers first and then calculate:
var pridatu = parseInt(uhrada) + parseInt(cena);

Jquery 1 + 1 = 11? [duplicate]

This question already has an answer here:
Simple Javascript Math Function- addition/not working?
(1 answer)
Closed 7 years ago.
I have a some problem on my jquery code.
I want counting 1 + 1 in jquery but the result is "11" not "2" ... so where the problem ??
Here is my code :
$(document).ready(function () {
var hasil = $(".hitdethasil>.hasildet");
var bhit = $(".hitung");
$(bhit).click(function(){
var ske = $(".iUn").val(); //assume is 1
var ska = $(".ia").val(); //assume is 1
var beda = $(".ib").val(); //assume is 1
var hasilarit = ska + (ske - 1) * beda; //but in this result is 10 should the result is 1.
$(hasil).text(hasilarit);
console.log(hasilarit);
});
$(".iUn").keyup(function () {
var thisis = $(this).val();
$(".skun").text(thisis);
});
});
Where does the fault ????
Thanks B4 and i'm sorry for my bad english ... :)
Here is JsFiddle to see the problem ... http://jsfiddle.net/bagusa4/mqLqoL7o/
This var ske = $(".iUn").val(); is "1" not 1. The same holds for the other textbox. So "1"+"1"="11", which is the expected.
Otherwise, you should use the parseInt -assuming that the input will be an integer. Otherwise you should use the parseFloat function-.
var ske = parseInt($(".iUn").val());

A function on checking if the string is a url in Javascript [duplicate]

This question already has answers here:
Check if a JavaScript string is a URL
(36 answers)
Closed 9 years ago.
I am writing a function to check if the input string is a url in Javascript. Should I use substring(0,6) and see if starts with "http://"? Or there is a better way to achieve? Cheers.
Something like this should handle the simple cases:
function is_url(url) {
return Boolean(url.match(/^https?:\/\//));
}
You could use a regular expression
/^http:\/\//.test(urlString)
You could use:
if(myvalue.indexOf('https://') == 0 || myvalue.indexOf('http://') == 0)
Depends how detailed you want to get with it. I am sure you can find a regex that would do it on here is you searched around.
With regex:
/^http:/.test("http://example.com/")
If you wanted to check www too: /^(http:|www\.)/.test("http://example.com/")
And to be different:
function matchString(str,matches)
{
if(matches)
{
matchString.toCheck=matches;
}
var matched = [];
for(var i=[0,str.length];i[0]<i[1]; i[0]++)
{
for(var j=[0,matchString.toCheck.length];j[0]<j[1]; j[0]++)
{
if(!matched[j[0]])matched[j[0]]={c:0,i:-1};
if(matchString.toCheck[j[0]][matched[j[0]].c]==str[i[0]])
{
matched[j[0]].c++;
if(matched[j[0]].i==-1)matched[j[0]].i=i[0];
}
else if(matchString.toCheck[j[0]].length!=matched[j[0]].c)matched[j[0]]={c:0,i:-1};
}
}
return matched;
}
var urlVariants = matchString("https://",["http://","https://","www."]);
var isUrl = false;
for(var i=[0,urlVariants.length]; i[0]<i[1]&&!isUrl; i[0]++)
{
isUrl = (urlVariants[i[0]].i==0);//index at the start
}
console.log(isUrl);
I think regex is a better solution:
function isAnUrl(url){
var expression = /[-a-zA-Z0-9#:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9#:%_\+.~#?&//=]*)?/gi;
var regex = new RegExp(expression);
if (url.match(regex))
return true;
else return false;
}

Pass Query string to WebMethod in Javascript [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Get query string values in JavaScript
What is the best way to get "test1" from
http://localhost:3311/blabl/allprofiles.aspx?username=test1
, and through PageMethod pass it to webmethod. I think one way is to take from window.location.pathname, cut the string and pass it like a parameter.
May be you can use only javascript like:
var search = function(){
var s = window.location.search.substr(1),
p = s.split(/\&/),
l = p.length,
kv, r = {};
if(l === 0){return false;}
while(l--){
kv = p[l].split(/\=/);
r[kv[0]] = kv[1] || true;
}
return r;
}();
Then use in your code search.username
Try
string username = Request.QueryString["username"];
In a PageMethod, you can do
string username = HttpContext.Current.Request.QueryString["username"];

how to check "contains" using jquery [duplicate]

This question already has answers here:
How to check whether a string contains a substring in JavaScript?
(3 answers)
Closed 9 years ago.
I tried of checking contains option using jquery for the birthday but its getting exception
var _dob = "4/10";
// this line doesn't work
var _adob = _dob.contains('/') ? _dob.Split('/') : _dob.Split('-');
$('#Month').val(_adob[0]);
$('#Day').val(_adob[1]);
but i can't able to split.. its resulting in error on getting _adob itself
Try this:
var _dob = "4/10";
var _adob;
if (_dob.indexOf("/") >-1) {
_adob = _dob.split("/");
} else {
_adob - _dob.split("-");
}
Direct Answer
indexOf(something)>-1
var _dob = "4/10";
var _adob = _dob.indexOf('/')>-1 ? _dob.split('/') : _dob.split('-');
$('#Month').val(_adob[0]);
$('#Day').val(_adob[1]);
Indirectly
You really don't need to check that the string contains that... Using a regular expression, you can split on a -, /, or . by building a character set:
var _dob = '4.10';
var _aodb = _dob.split(new RegExp('[-/.]'));

Categories

Resources