How to get a numeric value from a string in javascript? - javascript

Can anybody tell me how can i get a numeric value from a string containing integer value and characters?
For example,I want to get 45 from
var str="adsd45";

If your string is ugly like "adsdsd45" you can use regex.
var s = 'adsdsd45';
var result = s.match(/([0-9]+)/g);
['45'] // the result, or empty array if not found

You can use regular expression.
var regexp = /\d+/;
var str = "this is string and 989898";
alert (str.match(regexp));

Try this out,
var xText = "asdasd213123asd";
var xArray = xText.split("");
var xResult ="";
for(var i=0;i< xArray.length - 1; i++)
{
if(! isNan(xArray[i])) { xResult += xArray[i]; }
}
alert(+xResult);

var str = "4039";
var num = parseInt(str, 10);
//or:
var num2 = Number(str);
//or: (when string is empty or haven't any digits return 0 instead NaN)
var num3 = ~~str;
var strWithChars = "abc123def";
var num4 = Number(strWithChars.replace(/[^0-9]/,''));

Related

Separate characters and numbers from a string

I have a string variable that contain character and numbers like this
var sampleString = "aaa1211"
Note that variable always start with a character/s and end with number/s. Character and number size is not fixed. It could be something like followings
var sampleString = "aaaaa12111"
var sampleString = "aaa12111"
I need to separate the characters and numbers and assign them into separate variables.
How could I do that ?
I try to use split and substring but for this scenario I couldn't apply those. I know this is a basic question but i'm search over the internet and I was unable to find an answer.
Thank you
Please use
[A-Za-z] - all letters (uppercase and lowercase)
[0-9] - all numbers
function myFunction() {
var str = "aaaaAZE12121212";
var patt1 = /[0-9]/g;
var patt2 = /[a-zA-Z]/g;
var letters = str.match(patt2);
var digits = str.match(patt1);
document.getElementById("alphabets").innerHTML = letters;
document.getElementById("numbers").innerHTML = digits;
}
Codepen-http://codepen.io/nagasai/pen/pbbGOB
A shorter solution if the string always starts with letters and ends with numbers as you say:
var str = 'aaaaa12111';
var chars = str.slice(0, str.search(/\d/));
var numbs = str.replace(chars, '');
console.log(chars, numbs);
You can use it in a single regex,
var st = 'red123';
var regex = new RegExp('([0-9]+)|([a-zA-Z]+)','g');
var splittedArray = st.match(regex);
var num= splittedArray[0];
var text = splittedArray[1];
this will give you both the text and number.
Using Match
const str = "ASDF1234";
const [word, digits] = str.match(/\D+|\d+/g);
console.log(word); // "ASDF"
console.log(digits); // "1234"
The above will work even if your string starts with digits.
Using Split
with Positive lookbehind (?<=) and Positive lookahead (?=):
const str = "ASDF1234";
const [word, digits] = str.split(/(?<=\D)(?=\d)/);
console.log(word); // "ASDF"
console.log(digits); // "1234"
where \D stands for not a digit and \d for digit.
Use isNaN() to differentiate
var sampleString = "aaa1211"
var newnum =""
var newstr =""
for(var i=0;i<sampleString.length;i++){
if(isNaN(sampleString[i])){
newstr = newstr+sampleString[i]
}else{
newnum= newstr+sampleString[i]
}
}
console.log(newnum) //1121
console.log(newstr) //aaa
If you're like me, you were looking to separate alphabets and numbers, no matter what their position is, Try this:
var separateTextAndNum = (x) => {
var textArray = x.split('')
var text = []
var num = []
textArray.forEach(t=>{
if (t>-1) {
num.push(t)
} else {
text.push(t)
}
})
return [text, num]
}
For ex - if you try this:
separateTextAndNum('abcd1234ava') // result [["a","b","c","d","a","v","a"],["1","2","3","4"]]
This isn't beautiful but it works.
function splitLettersAndNumbers(string) {
var numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
var numbers, letters, splitIndex;
for (var i = 0; i < string.length; i++) {
if (numbers.indexOf(string[i]) > -1) {
letters = string.substring(0, i);
numbers = string.substring(i);
return [letters, numbers];
}
}
// in the chance that you don't find any numbers just return the initial string or array of the string of letters
return [string];
}
Essentially just looping through the string until you find a number and you split it at that index. Returning a tuple with your letters and numbers. So when you run it you can do something like this:
var results = splitLettersAndNumbers(string);
var letters = results[0];
var numbers = results[1];
A functional approach...
var sampleString = "aaaaa12111";
var seperate = sampleString.split('').reduce(function(start , item){
Number(item) ? start[0] += item : start[1] += item;
return start
},['',''])
console.log(seperate) //["12111", "aaaaa"]
You can loop through the string length, check it & add to the variable.
It is not clear if you want to assign each of the character to a variable or all alphabets to one variable & integers to another.
var sampleString = "aaa12111"
var _num = "";
var _alp = "";
for (var i = 0; i < sampleString.length; i++) {
if (isNaN(sampleString[i])) {
_num += sampleString[i];
} else {
_alp += sampleString[i];
}
}
console.log(_num, _alp)

How to split a number after n digits in javascript?

I have a number 2802 which is stored as a string in the backend. I want to split this number into 2 parts as 28 and 02 which should be shown as date 28/02? How can I do it with '/' in between them?
Try this : you can use substring as shown below. substring used for getting string between start index and end index. In your case, get string from 0 to 1 and then 2 to 3.
var str = "2802";
str = str.substring(0,2) + "/" + str.substring(2,4);
alert(str);
More information on Substring
Solution with regex
var res = "2802".match(/\d{2}/g).join('/');
document.write(res);
Are you asking about simple string manipulation?
var str = "1234";
var res = str.substr(0, 2)+"/"+str.substr(2,4);
You can do this:
var str = "2802";
str = str.split('').map(function(el, i){
if(i == 2){ el = '/'+el}
return el;
});
document.querySelector('pre').innerHTML = str.join('');
<pre></pre>
With regular expression:
var str = "2802";
str = str.replace(/(.{1,2}$)/gi, '/$1');
document.querySelector('pre').innerHTML = str;
<pre></pre>
var str = "2802";
var output = [str.slice(0, 2), str.slice(2)].join('/');
In this context conside 2802, 28 is date and 02 is month
Here 112, 028 what is date and month ?
A more generic solution could be
var num = 2802;
var output = String(num).match(new RegExp('.{1,2}', 'g')).join("/");
replace 2 with which ever number to split the number after n digits.
var n = 2;
var output = String(num).match(new RegExp('.{1,'+n+'}', 'g'));
var db_date = '112';
var date_str = '';
if(db_date.slice(0,1)==0){
var date_val = db_date.slice(0,2);
var month_val = db_date.slice(2,3);
if(month_val<=9){
month_val = '0'+month_val;
}
}else{
var date_val = db_date.slice(0,1);
date_val = parseInt(date_val);
if(date_val<=9){
date_val = date_val.toString();
date_val = '0'+date_val;
}
var month_val = db_date.slice(1,3);
}
alert(date_val+'/'+month_val);

Select 2 characters after a particular substring in javascript

We have a string ,
var str = "Name=XYZ;State=TX;Phone=9422323233";
Here in the above string we need to fetch only the State value i.e TX. That is 2 characters after the substring State=
Can anyone help me implement it in javascript.
.split() the string into array and then find the index of the array element having State string. Using that index get to that element and again .split() it and get the result. Try this way,
var str = "Name=XYZ;State=TX;Phone=9422323233";
var strArr = str.split(';');
var index = 0;
for(var i = 0; i < strArr.length; i++){
if(strArr[i].match("State")){
index = i;
}
}
console.log(strArr[index].split('=')[1]);
jsFiddle
I guess the easiest way out is by slicing and splitting
var str = "Name=XYZ;State=TX;Phone=9422323233";
var findme = str.split(';')[1];
var last2 = findme.slice(-2);
alert(last2);
Need more help? Let me know
indexOf returns the position of the string in the other string.
Using this index you can find the next two characters
javascript something like
var n = str.indexOf("State=");
then use slice method
like
var res = str.slice(n,n+2);
another method is :
use split function
var newstring=str.split("State=");
then
var result=newstring.substr(0, 2);
Check this:
var str1 = "Name=XYZ;State=TX;Phone=9422323233";
var n = str1.search("State");
n=n+6;
var res = str1.substr(n, 2);
The result is in the variable res, no matter where State is in the original string.
There are any number of ways to get what you're after:
var str = "Name=XYZ;State=TX;Phone=9422323233"
Using match:
var match = str.match(/State=.{2}/);
var state = match? match[0].substring(6) : '';
console.log(state);
Using replace:
var state = str.replace(/^.*State=/,'').substring(0,2);
console.log(state);
Using split:
console.log(str.split('State=')[1].substring(0,2));
There are many other ways, including constructing an object that has name/value pairs:
var obj = {};
var b = str.split(';');
var c;
for (var i=b.length; i; ) {
c = b[--i].split('=');
obj[c[0]] = c[1];
}
console.log(obj.State);
Take your pick.

How can I convert all numbers in a dataset of a DOM node into JavaScript numbers

I use the data attribute to store strings and numbers in DOM nodes and read them with JavaScript. Unfortunately all values in the dataset are saved as string. So whats is the best way to convert them into numbers but leave the strings.
html:
<input data-minvalue="10" data-startcolor="#00ee00"/>
expected result:
{
minvalue: 10,
startcolor:'#00ee00'
}
Edit:
it has to work with int and float
should not convert '12_test'
should convert '.3'
Precede the value by +, which will convert it to a number natively and preserves stuff like 12_test, which parseFloat does not. If the result isNaN, then safe the string instead.
function kittenBaloon(str) {
var num = +str;
if(isNaN(num)) {
return str;
} else {
return num;
}
}
console.log(kittenBaloon('12_test'));
console.log(kittenBaloon('.3'));
console.log(kittenBaloon('#00ee00'));
Use the Number function to parse numeric values. If it is not numeric, you get a NaN.
var dataset = el.dataset;
var data = {};
Object.keys(dataset).forEach(function (key) {
var num = Number(dataset[key]);
data[key] = isNaN(num) ? dataset[key] : num;
})
If parsing the attribute and checking for isFinite is not enough, you will have to test via regex whether you want to parse it as a number or not:
var obj = {};
for (var i=0; i<node.attributes.length; i++) {
var attr = node.attributes.length;
if (attr.name.substr(0, 5) == "data-")
obj[attr.name.substr(5)] = /^[+-]?(\d*\.)?\d+(e[+-]?\d+)?$/i.test(attr.value)
? parseFloat(attr.value)
: attr.value;
}
}
This regex orientates on the numeric string grammar as found in EcmaScript ยง9.3.1; yet it for example does not allow whitespaces.
You would use the parseInt() method.
After you pull the attr value for data-minvalue from the html you would pass it to parseInt() and use that as the value in your object.
assuming the use of jquery
var obj = {};
var strNum = $('selector').attr('data-minvalue);
var intNum = parseInt(strNum);
obj.minvalue = intNum;
var string1 = "#456456";
var string2 = "546.789";
var filterString = function (string) {
var temp = string;
regex1 = /\./;
regex2 = /\D/g;
temp = temp.replace(regex1, '');
if (!regex2.test(temp)) {
return parseFloat(string);
}
return string;
}
string1 = filterString(string1);
string2 = filterString(string2);
console.log(typeof string1); //returns string
console.log(typeof string2); //returns number

javascript - string numbers - convert from 123,456 to 123456

I have an array of string numbers like the follow:
"123,556","552,255,242","2,601","242","2","4"
and I would like to convert them to int numbers but the numbers with the "," I would like to convert from "123,556" to "123556" first.
How do I do so ?
var numbersArray = ["153,32","32,453,23","45,21"];
for (var i = 0; i < numbersArray.length; i++) {
numbersArray[i] = parseInt(numbersArray[i].replace(',',''));
}
var str = "552,255,242";
var numbr = parseInt(str.replace(/\,/g,''), 10);
You could use .replace method.
"123,556".replace(/,/g, '');
Try this: string.replace(',', '');
something like
var parseMe(myarray) {
var out = new Array(myarray.length);
for (i=0;i<myarray.length;i++){
var tokens[] = myarray[i].split(",");
var s = tokens[0] + tokens[1];
out.push(parseInt(s));
}
return out;
}
just use split, join (or replace) to remove the , and parseInt afterwards:
var number = "123,456";
number = number.split(',').join('');
number = parseInt(number, 10);

Categories

Resources