Number and Alphabet Separation in a String - javascript

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.

Related

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 ");
}
}

Checking the number inside a string in 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
}

Javascript IndexOf with integers in string not working

Can anyone tell me why does this not work for integers but works for characters? I really hate reg expressions since they are cryptic but will if I have too. Also I want to include the "-()" as well in the valid characters.
String.prototype.Contains = function (str) {
return this.indexOf(str) != -1;
};
var validChars = '0123456789';
var str = $("#textbox1").val().toString();
if (str.Contains(validChars)) {
alert("found");
} else {
alert("not found");
}
Review
String.prototype.Contains = function (str) {
return this.indexOf(str) != -1;
};
This String "method" returns true if str is contained within itself, e.g. 'hello world'.indexOf('world') != -1would returntrue`.
var validChars = '0123456789';
var str = $("#textbox1").val().toString();
The value of $('#textbox1').val() is already a string, so the .toString() isn't necessary here.
if (str.Contains(validChars)) {
alert("found");
} else {
alert("not found");
}
This is where it goes wrong; effectively, this executes '1234'.indexOf('0123456789') != -1; it will almost always return false unless you have a huge number like 10123456789.
What you could have done is test each character in str whether they're contained inside '0123456789', e.g. '0123456789'.indexOf(c) != -1 where c is a character in str. It can be done a lot easier though.
Solution
I know you don't like regular expressions, but they're pretty useful in these cases:
if ($("#textbox1").val().match(/^[0-9()]+$/)) {
alert("valid");
} else {
alert("not valid");
}
Explanation
[0-9()] is a character class, comprising the range 0-9 which is short for 0123456789 and the parentheses ().
[0-9()]+ matches at least one character that matches the above character class.
^[0-9()]+$ matches strings for which ALL characters match the character class; ^ and $ match the beginning and end of the string, respectively.
In the end, the whole expression is padded on both sides with /, which is the regular expression delimiter. It's short for new RegExp('^[0-9()]+$').
Assuming you are looking for a function to validate your input, considering a validChars parameter:
String.prototype.validate = function (validChars) {
var mychar;
for(var i=0; i < this.length; i++) {
if(validChars.indexOf(this[i]) == -1) { // Loop through all characters of your string.
return false; // Return false if the current character is not found in 'validChars' string.
}
}
return true;
};
var validChars = '0123456789';
var str = $("#textbox1").val().toString();
if (str.validate(validChars)) {
alert("Only valid characters were found! String validates!");
} else {
alert("Invalid Char found! String doesn't validate.");
}
However, This is quite a load of code for a string validation. I'd recommend looking into regexes, instead. (Jack's got a nice answer up here)
You are passing the entire list of validChars to indexOf(). You need to loop through the characters and check them one-by-one.
Demo
String.prototype.Contains = function (str) {
var mychar;
for(var i=0; i<str.length; i++)
{
mychar = this.substr(i, 1);
if(str.indexOf(mychar) == -1)
{
return false;
}
}
return this.length > 0;
};
To use this on integers, you can convert the integer to a string with String(), like this:
var myint = 33; // define integer
var strTest = String(myint); // convert to string
console.log(strTest.Contains("0123456789")); // validate against chars
I'm only guessing, but it looks like you are trying to check a phone number. One of the simple ways to change your function is to check string value with RegExp.
String.prototype.Contains = function(str) {
var reg = new RegExp("^[" + str +"]+$");
return reg.test(this);
};
But it does not check the sequence of symbols in string.
Checking phone number is more complicated, so RegExp is a good way to do this (even if you do not like it). It can look like:
String.prototype.ContainsPhone = function() {
var reg = new RegExp("^\\([0-9]{3}\\)[0-9]{3}-[0-9]{2}-[0-9]{2}$");
return reg.test(this);
};
This variant will check phones like "(123)456-78-90". It not only checks for a list of characters, but also checks their sequence in string.
Thank you all for your answers! Looks like I'll use regular expressions. I've tried all those solutions but really wanted to be able to pass in a string of validChars but instead I'll pass in a regex..
This works for words, letters, but not integers. I wanted to know why it doesn't work for integers. I wanted to be able to mimic the FilteredTextBoxExtender from the ajax control toolkit in MVC by using a custom Attribute on a textBox

Javascript extract numbers from a string

I want to extract numbers from a string in javascript like following :
if the string = 'make1to6' i would like to extract the numeric character before and after the 'to' substring in the entire string. i.e. 1 and 6 are to be extracted
The length of the string is not fixed and can be a max of 10 characters in length.The number can be of max two digits on either side of 'to' in the string.
Possible string values :
sure1to3
ic3to9ltd
anna1to6
joy1to4val
make6to12
ext12to36
thinking of something like :
function beforeTo(string) {
return numeric_value_before_'to'_in_the_string;
}
function afterTo(string) {
eturn numeric_value_after_'to'_in_the_string;
}
i will be using these returned values for some calculations.
Here's an example function that will return an array representing the two numbers, or null if there wasn't a match:
function extractNumbers(str) {
var m = /(\d+)to(\d+)/.exec(str);
return m ? [+m[1], +m[2]] : null;
}
You can adapt that regular expression to suit your needs, say by making it case-insensitive: /(\d+)to(\d+)/i.exec(str).
You can use a regular expression to find it:
var str = "sure1to3";
var matches = str.match(/(\d+)to(\d+)/);
if (matches) {
// matches[1] = digits of first number
// matches[2] = digits of second number
}

Categories