How to count the number of characters without "-" and "()"? - javascript

I have an input field for the phone numbers and field length counter. How can I ignore "-", spaces, and "()" in the field when I count its length?
I mean, if the input value looks like "(099) 99-99", its length when I call val().length should be 7, and not 11.
var phoneInput = getElementById("phone");
var counter = getElementById("lengthCounter");
counter.text(phoneInput.val().length);

By replacing all occurrences of that chars by empty string , then length of the output is what you are looking for.
const value = phoneInput.val();
value.replace(/[\-\(\)]/g, '').length // replace "-", "(", ")" by empty string
const phoneInput = document.querySelector('input');
const value = phoneInput.value;
console.log(
value.replace(/[\-\(\)]/g, '').length
)
<input value="(32)-(123)-(4444)" />

Try using regular expression.\D matches all the non-digit characters and the g is global modifier for regular expression.Replace all non-digits with empty string then count length of your string.
var string = "(099) 99-99";
console.log(string.replace(/\D/g,'').length);

This will replace anything that is NOT a number with an empty sting.
counter.text(phoneInput.val().replace(/[^\d]/g, '').length)

Replace none digit (\D) by "" and then count the length of new string.
var phoneNum = "(+84) 122 - 384 - 6471";
var count = phoneNum.replace(/\D/g, "").length;
alert(count);

Check this out! no need to write many lines of code.
function count() {
var x = document.getElementById("phonenumber");
var count = x.value.replace(/[^0-9]/g,"").length;
$("#displaycount").text("Number Count "+count);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Enter your Number: <input type="text" placeholder="example (99) 99-999" id="phonenumber" onkeyup="count()">
<br/><br/>
<div id="displaycount"></div>

Related

How to process string so to keep characters up to last digit?

Given strings such as G08a, Professor3, Obs...
How to slice these strings after the last digit, so it returns :
G08a ==> G08
Professor3 ==> Professor3
Obs ==> Obs
Starting jsfiddle : https://jsfiddle.net/dpyqg2mk/
You can use a regex for this.
var ss = ["G08a", "Professor3", "Obs"];
var res = ss.map(s => (/^(.*?\d)\D*$/.exec(s) || [,s])[1]);
console.log(res);
This collects all characters up through a digit that is followed by a series of zero or more non-digits that continue to the end of the string. The initial characters and that last digit before the non-digits are captured in a group.
I used .map() as a convenience for the demo, and substituted a temporary array when the regex finds no match.
Short and simple:
let str = "foo9bar";
str = str.match(/(.*\d)|(.*\d?)/g)[0]; // str is now foo9
let elem = document.getElementById('txt');
elem.innerHTML = elem.innerHTML.match(/(.*\d)|(.*\d?)/g)[0];
<p id="txt">foo9bar</p>
First you need to find first digit' position in string
var str = "G08a";
var match = str.match(/(\D+)?\d/)
var index = match ? match[0].length-1 : -1;
Then make substring
var result =str.substring(0,index);
You could match the string by using a search for any character foolowd by a digit or any character which are followed ba a non digit or end of string.
console.log(['G08a', 'Professor3', 'Obs', 'abc123def456ghi'].map(function (s) {
return s.match(/^.*\d|.*(?=\D|$)/)[0];
}));

discard count of \n in a string while using string.length in Javascript

"HelloWorld" consists of 10 characters
I have a string as
var temp = "Hello\nWorld"
When I use temp.length it returns 11 as it counts \n as a character. How do I only count characters?
You have to firstly remove the \n:
temp.replace(/\n/g, '').length
String will still be:
temp = "Hello\nWorld"
Use match() to get count of line breaks and subtract from total length
var str = 'Hello\nWorld\n';
var breaks =str.match(/\n/g);
var count = str.length - (breaks ? breaks.length : 0);
alert(count)
Alternative solution
temp.match(/\w/g).length;
"Hello\nworld" returns 11 characters because \n also is a character.
so if you want to count how much characters in string, you need to remove any \n or \s firstly in .length

Javascript string replace on non numeric and letter s

var value = document.getElementById("height_"+ rowCount).value;
value = value .replace("a", "");
document.getElementById("height_"+rowCount).value = value;
Above is a javascript example that I used to replace the letter "a" in my text field height_row e.g height_1 (for row 1)
I want to able to filter all input except
0 to 9, letter s,
how do I auto replace all input with blank if its not number 0 to 9 or letter "s"
Thanks for helping
Use a regular expression:
var rowCount = 1;
var value = document.getElementById("height_"+ rowCount).value;
value = value.replace(/[^0-9s]/g, "");
document.getElementById("height_"+rowCount).value = value;
<input type="text" value="one 1 two 2 three 3 numbers" id="height_1" />

get only number from value and calculate the length from text field

I HAVE A TEXT FIELD
<input id="prime-phone" class="number-format" name="prime-phone" placeholder="" type="tel">
and there if fix value and it would be "(432)432-2432".
I want to count the length of number only not the special character like "(" , "-"
I am trying in this way and i also know i am doing somthing wrong
sd = $(".number-format").val();
alert(sd);
sd = parseInt(sd)
alert(sd)
number format can be change like "(432)432-2432" , "(43)-(432)-2432"
Thanks
in advance for the help :)
var sd = $(".number-format").val();
//i want to count the length of number only not the special character like "(" , "-"
var len = sd.match(/\d/g).length;
try it
Use regex to match the digits and count:
sd.match(/\d/g).length
Remove non digit character using replace() and count
sd=$(".number-format").val();
alert(sd);
len=sd.replace(/\D/g,'').length;
// \D used to match all non-digit character
alert(len);
DEMO
A reusable solution.
once defined you could just call them to exclude the unwanted characters and get the length.i find this easier to maintain.
var tel = "(432)432-2432";
var getLength = function(tel){
var telStr = tel.split('');
var excpetionList = ['(',')','-']; //<-- here you can add the chars to remove
return telStr.filter(function(item,index,arr){
if(excpetionList.indexOf(item) < 0){
return item;
}
}).join('').length;
};
console.log(getLength(tel));
demo

Parsing number from string

How do I split selected value, seperate the number from text in jQuery?
Example:
myselect contains c4
Just get only the number 4.
$('select#myselect').selectToUISlider({
sliderOptions: {
stop: function(e,ui) {
var currentValue = $('#myselect').val();
alert(currentValue);
var val = currentValue.split('--)
alert(val);
}
}
});
You can use regex to pull only the numbers.
var value = "c4";
alert ( value.match(/\d+/g) );
edit: changed regex to /\d+/g to match numbers greater than one digit (thanks #Joseph!)
1) if it's always : 1 letter that followed by numbers you can do simple substring:
'c4'.substring(1); // 4
'c45'.substring(1); // 45
2) you can also replace all non-numeric characters with regular expression:
'c45'.replace(/[^0-9]/g, ''); // 45
'abc123'.replace(/[^0-9]/g, ''); // 123
If you know that the prefix is always only one character long you could use this:
var val = currentValue.substr(1);

Categories

Resources