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

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

Related

RegEx to check first two characters must be "1 (numaric)-" in 9 letter word remaing should be alphanumaric

I tried coding in such way that code was not working
var redEx = /^1-[0-9a-zA-Z]{7}/;
document.getElementById("rowidOpty").value.test(redEx)
Example: '1-5S6AW2R': in the string first letter should be numeric and
second character must be "-" and remain alpha-numeric.
It's regexObj.test(string) instead of string.test(regexObj).
See RegExp.prototype.test() for more information.
console.log(/^1-[0-9a-zA-Z]{7}/.test('1-5S6AW2R'))
You have wrong function syntax:
regexp.test([str])
And the right one is:
var regEx = /^1-[0-9a-zA-Z]{7}/;
var string = '1-5S6AW2R';
console.log(regEx.test(string));
pattern = /^[0-9]-(\w+)/g;
console.log('1-5S6AW2R'.match(pattern))
Try this pattern ^[0-9]-(\w+)
Demo Regex
If you want to validate the input matches exactly one numeric, one dash and 7 alphanumerics exactly, use this:
/^[0-9]-[a-zA-Z-0-9]{7}$/;
or if the first can be only the numeral 1:
/^1-[a-zA-Z-0-9]{7}$/;
If you want to search for all occurrences of this pattern in a string that contains a lot of text:
/(^|\s)[0-9]-[a-zA-Z-0-9]{7}(\s|$)/g;
var restrictivePattern = /^[0-9]-[a-zA-Z-0-9]{7}$/;
var loosePattern = /(^|\s)[0-9]-[a-zA-Z-0-9]{7}(\s|$)/g;
var str = '1-A78Z2TE';
var longStr = 'We have 2 different codes 1-AYRJ3F4 and 4-23RJ3F4';
console.log("Validation of string to match pattern: ", str.match(restrictivePattern))
console.log("Multiple matches in string: ", longStr.match(loosePattern))

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

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>

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

Jquery check if special char exists in text value

i need to check if a textarea contains some special characters, so i need to count them 2 (SMS lenght).
I wrote this piece of code but seems that it doesn't find no special chars, also if write only "€€€"
Could you please help me? Also if you would to rewrite directly function, without problem. Thank tou!
var SPECIAL_CHARS = Array('€', '%');
function charUsed() {
var count = $('#text').val().length;
var chars = $('#text').val().split("");
var numberOfSpecialChars = 0;
if ($.inArray(chars, SPECIAL_CHARS) > -1) {
numberOfSpecialChars++;
}
return count + numberOfSpecialChars;
} // function
A rewrite :
var nbSpecialChars = $('#text').val().split(/[€%]/).length - 1;
The idea is to make an array of strings, using your special characters as separator :
'some € chars %' => ["some ", " chars ", ""]
and then use the length of this array to deduce the count of those chars. There are many other (faster) solutions but this one is short.
http://jsfiddle.net/KSm7J/
var chars = $('#text').val().match(/[€%]/g).length;
alert(chars);

How to check for uppercase alphabets in an input string, using jQuery

I am using following code snippet, but its not working :-(
//First four characters of input Text should be ALPHABATES (Letters)
if (($("#txtId").val()).length >= 4) {
var firstFourChars = $("#txtId").val().substring(0, 4);
var pattern = new RegExp('[^A-Z]');
if (firstFourChars.match(pattern))
isValid = true;
else
isValid = false;
}
change /[^A-Z]/ to /^[A-Z]/
example :
var a = "ABCJabcd";
console.log(a.match(/^[A-Z]{4}/));
you don't need to use substring(). Your regexp can do all the work for you. The RegExp you are using matches against characters that are NOT between A and Z. As Avinash said, ^[A-Z]{4} will match if your first 4 characters are uppercase. "^" at the beginning of your regexp tells that the following should be the beginning of the string. When placed inside square brackets, it reverts the range of characters you want to match.
The regex should be /[^A-Z]{4}/ if you want to match the 4 lowercase characters.
To detect in the middle of the big papers change /^[A-Z]/ to /[A-Z]/
Example text: " asşldla ABCJ abcd AÇALASD"
$('.Order input').change(function (){ucheck($(this).val())});
$('.Order input').keyup(function (){ucheck($(this).val())});
function ucheck(a) {
if(a.match(/[A-ZĞÜŞİÖÇ]{4}/)){
$('.Order #Error').html(' UPPERCASE');
}else{$('.Order #Error').html('Capitalize');}
}
If they need to be capital:
const startsWithCapitals = /^[A-Z]{4}/.test(string);
Or if they just need to be letters, add an i for ignore case:
const startsWithLetters = /^[a-z]{4}/i.test(string);
^ means start of the string and {number} means x copies

Categories

Resources