Checking the number inside a string in javascript - javascript

I have a string, say
var Str = 'My name is 123 and my name is 234'.
Now I split this as
var arrStr = Str.split(' ');
I iterate through the array and have different logic depending upon whether the word is a string or number. How do i check that? I tried typeof which didn't work for me.
EDIT:
After Seeing multiple answers. Now, I am in despair, which is the most efficient way?

If you care only about the numbers, then instead of using split you can use a regular expression like this:
var input = "My name is 123 and my name is 234";
var results = input.match(/\d+/g)
If you care about all pieces, then you can use another expression to find all non-space characters like this:
var input = "My name is 123 and my name is 234";
var results = input.match(/\S+/g)
Then iterate them one by one, and check if a given string is a number or not using the famous isNumeric() function posted by #CMS in this famous question.
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
NOTE: Thanks to #Pointy and if you want them as numbers, input.match(/\d+/g).map(Number).

You need to attempt to convert your array values to an integer.
To iterate them you can use a for loop:
for(i=0;i<arrStr.length;i++) {
var result = !isNaN(+arrStr[i]) ? 'number' : 'string';
console.log(result);
}
Here I'm using a unary + to attempt to convert the value of each array value to a number. If this fails, the result will be NaN. I'm then using JavaScript's isNaN() method to test if this value is NaN. If it isn't, then it's a number, otherwise it's a string.
The result of this using the string you've provided is:
string
string
string
number
string
string
string
string
number
To use this in an if statement, we can simply:
for(i=0;i<arrStr.length;i++) {
if(isNaN(+arrStr[i])) {
/* Process as a string... */
}
else {
/* Process as a number... */
}
}
JSFiddle demo.

To expound on Sniffer's answer...
var input = "My name is 123 and my name is 234";
var numberArray = input.match(/\d+/g);
var wordArray = input.match(/[A-Za-z]+/g);
for (var number in numberArray)
{
//do something
}
for (var word in wordArray)
{
//do something
}

While researching, I found out about the Number() object. This is generally used to work with manipulation of numbers. MDN has a good documentation .
I found out that Number() returns NaN (Not a Number) when not passed a number. Since no number returns NaN, It could be a good way to check whether the passed object is string or a number literal.
So my code would be:
if (Number(arrStr[i]) == NaN){
//string
} else {
//number
}

Related

toString not getting applied to mixture of numbers, characters and special symbols

I am trying below code:-
var testrename = {
check: function() {
var str = 988,000 PTS;
var test = str.toString().split(/[, ]/);
console.log(test[0] + test[1]);
}
}
testrename.check();
I want output as- 988000
I was trying it on node
Your str variable's assigned value needs to be quoted in order to assign a string value to it, and for it to be recognized as a string.
It looks like what you're trying to do is extract the integer value of a string, so return 988000 from the string "988,000 PTS", and you would use parseInt(string) for that.
Update: The comma will break the parseInt function and return a truncated number, (988 not 988000) so you can use the replace function with a regular expression to remove all non-numeric values from the string first.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt
var testrename={
check :function() {
var str ="988,000 PTS";
cleanStr = str.replace(/\D/g,'');
var test = parseInt(cleanStr);
console.log(test);
}
} testrename.check();

How to check if an object in an array is a number or a text?

I run:
var string = "27 - 28 August 663 CE";
var words = string.split(" ");
for (var i = 0; i < words.length - 1; i++) {
words[i] += " ";
}
And I get an array like:
["27","-","28","August","663","CE"]
How would I iterate with that array and loop it to find if an object is a text string or a number?
To be perfectly correct, these are all of the type string, because they are between quotes. I guess you want to find out if these strings can be converted to a number. You can check this with isNan(), gives false when numeric and true when not. You can actually convert the string to a number (integer) with parseInt();
var array = ["27","-","28","August","663","CE"];
for (var el of array) {
if(!isNaN(el)) { // check if el is numeric
el = parseInt(el); // parse el to a int
console.log("This element is numeric");
console.log(el);
}
}
You can use the jQuery $.isNumeric() inside a $.each loop
$.each(words,function(){
if($.isNumeric(this)) {
//code to execute if number
}
})
You can use Number(), which returns NaN if string is non-numeric. One thing to keep in mind is that Number('') === 0.
for (const word of words.split(' ')) {
if (isNaN(Number(word)) {
//code if non-numeric
}
else {
//code if numeric
}
}
you can use Number() directly
var arr = ["0","-","28","August","663","CE"]
function isNumber(str) {
return str && isNaN(Number(str)) ? false : true
}
arr.forEach((item) => {
console.log(isNumber(item))
})
var string = "27 - 28 August 663 CE";
var words = string.split(" ");
for (var i = 0; i < words.length; i++) {
console.log(/\d+/g.test(words[i])); // RegExp way (possible only with input formatted like string you specified)
console.log(/^[\d]+(.[\d]+)*$/g.text(words[i])); // RegExp way that would consider floats, ints as a number and would not consider strings like "123aaa" as a number
console.log(!isNaN(parseInt(words[i]))); // NaN with parseInt way
console.log(!isNaN(words[i])); // only NaN way - warning: strings like "123aaa" are considered as a number as parseInt would create an int
with vale of 123
console.log(!isNan(Number(words[i])) && words[i] !== ''); // csadner's solution with Number
// all above logs will output true if the string is a number
}
This should probably solve the problem. What's going on here is:
Regular expression checks if provided string contains only the numbers
parseInt will return NaN (Not a Number) on fail, so we check if the returned value is not NaN.
isNaN itself checks if string is a number - in case you don't want to have hexadecimals, etc.
In the for loop you already have, you can determine if it's NOT a number with this condition:
!words[i] || isNaN(words[i])
If that is true, it's not a number

javascript program to check if a string is palindromes not returning false

I wrote this bit of code a a part of an exercise to check weather or not a string is palindromes. They program is working correctly in terms of checking the string but it does not return false when the string is not palindromes. What am I doing wrong? thanks
//convert the string to array
var stringArr = [ ];
var bool;
function palindrome(str) {
// make lowercase
var lowerCase = str.toLowerCase();
//remove numbers, special characters, and white spaces
var noNumbers = lowerCase.replace(/[0-9]/g, '');
var noSpecials = noNumbers.replace(/\W+/g, " ");
var finalString = noSpecials.replace(/\s/g, '');
stringArr = finalString.split("");
if (stringArr.sort(frontToBack)==stringArr.sort(backToFront)) {
bool = true;
}
else {
bool= false;
}
return bool;
}
function frontToBack (a,b) {return a-b;}
function backToFront (a,b) {return b-a;}
palindrome("eye");
if (stringArr.sort(frontToBack)==stringArr.sort(backToFront)) { is your problem.
In JavaScript, the sort method updates the value of the variable you are sorting. So in your comparison, once both sort's have run, both end up with the same value (since the second sort, effectively overrides the first).
For example.
var a = [1,7,3];
a.sort();
console.log(a); // will print 1,3,7
Edit: had a quick test, I think eavidan's suggestion is probably the best one.
Edit2: Just put together a quick version of a hopefully working palindrome function :)
function palindrome(str) { return str.split("").reverse().join("") == str;}
It is because string subtraction yields NaN, which means both sorted arrays are the same as the original.
Even if you did convert to ASCII coding, you sort the entire string, then for instance the string abba would be sorted front to back as aabb and back to front as bbaa. (edit: and also what Carl wrote about sort changing the original array. Still - sort is not the way to go here)
What you should do is just reverse the string (using reverse on the array) and compare.
You might do as follows;
var isPalindrome = s => { var t = s.toLowerCase()
.replace(/\s+/g,"");
return [].slice.call(t)
.reverse()
.every((b,i) => b === t[i]);
};
console.log(isPalindrome("Was it a car or a cat I saw"));
console.log(isPalindrome("This is not a palindrome"));
function pal()
{
var x=document.getElementById("a").value;
//input String
var y="";
//blank String
for (i=x.length-1;i>=0;i--)
//string run from backward
{
y=y+x[i];
//store string last to first one by one in blank string
}
if(x==y)
//compare blank and original string equal or not
{
console.log("Palindrome");
}
else
{
console.log("Not Palindrome ");
}
}

Number and Alphabet Separation in a String

I have String variables in Javascript like :
var houseNo = "62A"; var cabinNo = "5BC";
I need to fetch out the Integers and the Alphabets separate from the string where number of occurrences of each can be any number of times.
Need help to do it in the best possible way, be it through lodash or any other prototype method.
Referred to this but left in vain as don't want it through RegEx.
something like :
function decompose(string){
for(var i=0;i<string.length;i++){
if(parseInt(string[i])){ // if the char is a number?
// do whatever you want
}else{
// it's a character
}
}
}
The parseInt() function return the number of a giver char. If it is not a number, it returns NaN (not a number). if(parsInt(char)) return false if it's a char, true if it's a number
Try this:
var houseNo = "62A";
foreach(char a in houseNo)
{
if(a > 48 && a < 57)
{
/*it's a number*/
}
else
{
/*it's a letter*/
}
}
You can apply it on every string and determine what you want to do with each number or letter.
var test = "a3434dasds3432s2"
var myString = test.split("").filter(function(v) {return isNaN(v)}).join("")
var myNumber = parseInt(test.split("").filter(function(v) {return !isNaN(v)}).join(""))
best to use regex really though.

javascript parseInt when value = 0

I'm using jquery.grep to clean a string and return only digits.
This is what I have:
var TheInputArray = TheInput.slice();
var TheCleanInput = jQuery.grep(TheInputArray, function (a) {
return parseInt(a, 10);
});
I take a string, split it into an array and use the parseInt function to check if it's a number. The problem is that when the value of a is 0, it skips that element. What changes do I need to do to make this code work?
Thanks.
Unfortunately, 0 in Javascript is falsy. So you need to be sure your return value is true, even for a 0.
var TheInputArray = TheInput.slice();
var TheCleanInput = jQuery.grep(TheInputArray, function (a) {
return ! isNaN(parseInt(a, 10));
});
parseInt returns NaN (not a number), if it fails to parse the input. And isNan() will return true if the argument is NaN. So this should help you detect that case.
You can use regular expressions:
var TheCleanInput = TheInput.replace(/\D/g, '');
If you just want to test whether the element in the array is a number, rather than converting it and then building a new array using the converted numbers, you can use the new $.isNumeric function (new in 1.7), which tests whether the argument represents a numeric value:
var TheCleanInput = jQuery.grep(TheInputArray, function (a) { return $.isNumeric(a); });
Note that this does not modify the existing array. If the array contains '5', that will remain a string and not be converted to a number. Use $.map if that's what you want.
The parseInt() function doesn't return a boolean value, it either returns NaN for non-numeric values or the converted value for numeric values. If you try to use the result as a boolean you'll find that NaN and 0 will both be falsy, while any non-zero number will be equivalent to true.
You can use isNan() to check this: return !isNan(parseInt(a,10));
Or you can use jQuery's $.isNumeric(a) function instead (if using jQuery 1.7+).
Or if you just want to remove all non-numeric characters from a string why not use a regex replace:
TheInput.replace(/\D/g,"")
Even if you specifically want the result as an array I think you're best off using the regex and then converting to an array afterwards because it keeps the code simple.
If you're using the current Version of jQuery (1.7), you can use jQuery.isNumeric(a) for that purpose:
var TheCleanInput = jQuery.grep(TheInputArray, function (a) { return $.isNumeric(a); });
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
var filterInt = function(value) {
if (/^(\-|\+)?([0-9]+|Infinity)$/.test(value))
return Number(value);
return NaN;
}

Categories