How do i get only number in javascript [duplicate] - javascript

This question already has answers here:
how to extract floating numbers from strings in javascript
(3 answers)
Closed 4 years ago.
I have string like
11.7 km
and I need get only int( 11.7 ), how can I do this with JavaScript?
Thanks.

Try the parseInt().
Example:
var string = "11.7 km";
alert(parseInt(string));
This would alert: "11".
In your case you have a float, so you could use:
alert(parseFloat(string));
This gives an alert with "11.7".
ParseFloat reference
ParseInt reference

You can use replace method by passing a regex expression as argument.
console.log('11.7 km'.replace(/[^0-9.]/g, ''));

Try This.
var numbers = distance.replace(/[^0-9.]/g,'');
alert(numbers);

You can use parseFloat('11.7km') this will return 11.7

You can also use this.
console.log(Number(("11.7 km").replace(/[^\d.-]/g, '')));

This regular expression will match all numerical values in a string, regardless of text before or after the value.
var str = "11.7 km\n" +
"Text before 11.7 km\n" +
"11.7 km Text after\n" +
"Text before 11.7 km Text after\n";
var matches = str.match(/(\.\d*)*\d+(\.\d*)*/igm).map(parseFloat);
console.log('string "' + str + '" has ' + matches.length + " matches:");
console.log(matches);

The solution you can use is a Regular Expression, using the match function:
your_text = "11.7 km";
r = new RegExp("\\d|\\.","g");
matched_number = your_text.match(r);
number = matched_number.join("");
number_float = parseFloat(number)

Related

Format string '1,200' to integer 1200, with javascript [duplicate]

This question already has answers here:
How can I parse a string with a comma thousand separator to a number?
(17 answers)
Convert string to int in jquery and delete comma in string
(7 answers)
Closed 1 year ago.
I have a problem convert string 1,200 to integer 1200
i need convert 1,200 to 1200 integer
how to solve my problem using javascript ?
You can split on the comma, rejoin and parse into a number,
or remove the commas with a regex and parse into a number
Note that both of these methods allow for more than 1 ',' eg if 1,000, 000 - that's what the g is for in the regex.
const str = '1,200'
const option1 = parseInt(str.split(',').join(''), 10);
const option2 = parseInt(str.replace(/,/g,''), 10);
console.log('option1 - split and join - then parse: ' + option1);
console.log('option2 - replace with regex - then parse: ' + option2);
To work in node and browser, use replace with regex.
const num = "1,200"
const parsed = Number(num.replace(/,/g, ""))
You can first replace all commas (with String.replaceAll), then parse:
const str = "1,200"
const parsed = +str.replaceAll(',', '')
console.log(parsed)

Formatting numbers with regex JavaScript [duplicate]

This question already has answers here:
How to format numbers as currency strings
(67 answers)
Closed 9 years ago.
I'm trying to format a number as brazilian currency, but I'm not sure what's going wrong.
function format2(n, currency) {
return currency + " " + n.toFixed(2).replace(^\s*(?:[1-9]\d{0,2}(?:\.\d{3})*|0)(?:,\d{1,2})?$/g, "$1,");
}
Taken from the comments: “but its giving me a syntax error..”
You're missing a slash to define a regex literal. Change your return statement to
return currency + " " + n.toFixed(2).replace(/^\s*(?:[1-9]\d{0,2}(?:\.\d{3})*|0)(?:,\d{1,2})?$/g, "$1,");
^ Teda, the magic opening slash!
Btw, your regex is too complex IMO and doesn't format correctly. I would just do /\./g to get the matching periods, so your replace statement looks like .replace(/\./g, ",");
Demo
I don't know why you're so keen to use a regular expression for this. The following loop solution should be fine and offers a more general solution:
function formatNumber(num, places, thou, point) {
var result = [];
num = Number(num).toFixed(places).split('.');
var m = num[0];
for (var s=m.length%3, i=s?0:1, iLen=m.length/3|0; i<=iLen; i++) {
result.push(m.substr(i? (i-1)*3+s : 0, i? 3 : s));
}
return result.join(thou) + point + num[1];
}
console.log('R$ ' + formatNumber(12345678.155, 2, '.', ',')); // R$ 12.345.678,16
console.log('R$ ' + formatNumber(12.155, 2, '.', ',')); // R$ 12,16

How to trim a string to its last four characters? [duplicate]

This question already has answers here:
How to get the last character of a string?
(15 answers)
Closed 8 years ago.
I know there are methods to remove characters from the beginning and from the end of a string in Javascript. What I need is trim a string in such a way that only the last 4 characters remain.
For eg:
ELEPHANT -> HANT
1234567 -> 4567
String.prototype.slice will work
var str = "ELEPHANT";
console.log(str.slice(-4));
//=> HANT
For, numbers, you will have to convert to strings first
var str = (1234567).toString();
console.log(str.slice(-4));
//=> 4567
FYI .slice returns a new string, so if you want to update the value of str, you would have to
str = str.slice(-4);
Use substr method of javascript:
var str="Elephant";
var n=str.substr(-4);
alert(n);
You can use slice to do this
string.slice(start,end)
lets assume you use jQuery + javascript as well.
Lets have a label in the HTML page with id="lblTest".
<script type="text/javascript">
function myFunc() {
val lblTest = $("[id*=lblTest]");
if (lblTest) {
var str = lblTest.text();
// this is your needed functionality
alert(str.substring(str.length-4, str.length));
} else {
alert('does not exist');
}
}
</script>
Edit: so the core part is -
var str = "myString";
var output = str.substring(str.length-4, str.length);

javascript search string contains ' + '

i would to search a string into another string but i'm facing an issue.
There is my code :
reference = "project/+bug/1234";
str = "+bug/1234";
alert(reference.search(str));
//it should alert 8 (index of matched strings)
but it alert -1 : so, str wasn't found into reference.
I've found what's the problem is, and it seems to be the " + " character into str, because .search("string+str") seems to evaluate searched string with the regex " + "
Just use string.indexOf(). It takes a literal string instead of converting the string to a RegExp object (like string.search() does):
> reference = "project/+bug/1234";
> str = "+bug/1234";
> console.log(reference.indexOf(str));
8
Try this:
reference = "project/+bug/1234";
str = "+bug/1234";
alert(reference.indexOf("+bug/1234"));

Javascript string formatting, short question

How can I use javascript to add a number (any number between 0-100) followed by a underscore, before the variable value?
Example:
2000 becomes 12_2000 //a number of my choice is added followed by an underscore
hello becomes 12_hello
The number (12 in this case) is a constant chosen by me!
Thanks
i + '_' + x where i is the number and x is an arbitrary value.
Just use string concatenation:
var res = '12_' + myNum;
Or with a variable prefix:
var res = prefix + '_' + myNum;
This is just basic string concatenation, which can be done with the + operator:
var num = 2000;
"12_" + num;
// "12_2000"
var_name = "2000";
output = "12_" + var_name;
function prefixWithNumber(value, number) {
return number + "_" + value;
}
This expression is evaluated as (number + "_") + value. Since one of the operants in the first addition is a string literal, the second argument number is converted (coerced) to a string. The result is a string, which causes the third argument to be converted to a string as well.
This is what the JS engine does behind the scenes:
(number.toString() + "_") + value.toString();
Maybe you're looking for something like this:
Object.prototype.addPrefix = function(pre){
return pre + '_' + this;
};
This allows code like:
var a = 5;
alert(a.addPrefix(7));
or even:
"a string".addPrefix(7);
Joining an array can be faster in some cases and more interesting to program than "+"
[i, '_', myNum].join('')

Categories