jQuery - check whether string contains numeric value - javascript

How to check whether a string contains any numeric value by jquery?
I search through many examples but I only get the way to check for a number, NOT number in a STRING. I am trying to find something like $(this).attr('id').contains("number");
(p/s: my DOM id will be something like Large_a (without numeric value) , Large_a_1 (with numeric value), Large_a_2, etc.)
What method should I use?

You could use a regular expression:
var matches = this.id.match(/\d+/g);
if (matches != null) {
// the id attribute contains a digit
var number = matches[0];
}

This code detects trailing digits preceded by the underscore symbol (azerty1_2 would match "2", but azerty1 would not match):
if (matches = this.id.match(/_(\d)+$/))
{
alert(matches[1]);
}

Simple version:
function hasNumber(s) {
return /\d/.test(s);
}
More efficient version (keep regular expression in a closure):
var hasNumber = (function() {
var re = /\d/;
return function(s) {
return re.test(s);
}
}());

Related

Determine if string has any characters that aren't in a list of characters and if so, which characters don't match?

I'm working on a simple password validator and wondering if its possible in Regex or... anything besides individually checking for each character.
Basically if the user types in something like "aaaaaaaaa1aaaaa", I want to let the user know that the character "1" is not allowed (This is a super simple example).
I'm trying to avoid something like
if(value.indexOf('#') {}
if(value.indexOf('#') {}
if(value.indexOf('\') {}
Maybe something like:
if(/[^A-Za-z0-9]/.exec(value) {}
Any help?
If you just want to check if the string is valid, you can use RegExp.test() - this is more efficient that exec() as it will return true when it finds the first occurrence:
var value = "abc$de%f";
// checks if value contains any invalid character
if(/[^A-Za-z0-9]/.test(value)) {
alert('invalid');
}
If you want to pick out which characters are invalid you need to use String.match():
var value = "abc$de%f";
var invalidChars = value.match(/[^A-Za-z0-9]/g);
alert('The following characters are invalid: ' + invalidChars.join(''));
Although a simple loop can do the job, here's another approach using a lesser known Array.prototype.some method. From MDN's description of some:
The some() method tests whether some element in the array passes the test implemented by the provided function.
The advantage over looping is that it'll stop going through the array as soon as the test is positive, avoiding breaks.
var invalidChars = ['#', '#', '\\'];
var input = "test#";
function contains(e) {
return input.indexOf(e) > -1;
}
console.log(invalidChars.some(contains)); // true
I'd suggest:
function isValid (val) {
// a simple regular expression to express that the string must be, from start (^)
// to end ($) a sequence of one or more letters, a-z ([a-z]+), of upper-, or lower-,
// case (i):
var valid = /^[a-z]+$/i;
// returning a Boolean (true/false) of whether the passed-string matches the
// regular expression:
return valid.test(val);
}
console.log(isValid ('abcdef') ); // true
console.log(isValid ('abc1def') ); // false
Otherwise, to show the characters that are found in the string and not allowed:
function isValid(val) {
// caching the valid characters ([a-z]), which can be present multiple times in
// the string (g), and upper or lower case (i):
var valid = /[a-z]/gi;
// if replacing the valid characters with zero-length strings reduces the string to
// a length of zero (the assessment is true), then no invalid characters could
// be present and we return true; otherwise, if the evaluation is false
// we replace the valid characters by zero-length strings, then split the string
// between characters (split('')) to form an array and return that array:
return val.replace(valid, '').length === 0 ? true : val.replace(valid, '').split('');
}
console.log(isValid('abcdef')); // true
console.log(isValid('abc1de#f')); // ["1", "#"]
References:
JavaScript conditional operator (assessment ? ifTrue : ifFalse).
JavaScript Regular Expressions.
String.prototype.replace().
String.prototype.split().
RegExp.prototype.test().
If I understand what you are asking you could do the following:
function getInvalidChars() {
var badChars = {
'#' : true,
'/' : true,
'<' : true,
'>' : true
}
var invalidChars = [];
for (var i=0,x = inputString.length; i < x; i++) {
if (badChars[inputString[i]]) invalidChars.push(inputString[i]);
}
return invalidChars;
}
var inputString = 'im/b#d:strin>';
var badCharactersInString = getInvalidChars(inputString);
if (badCharactersInString.length) {
document.write("bad characters in string: " + badCharactersInString.join(','));
}

Removing all instances of a character from a string

I'm attempting to remove all instances of a given set of characters £$€,. from a string in jQuery/Javascript. I'm using the replace function, however this only appears to remove a single instance of the character and not all of them.
For example consider the string:
1,500,00.00.$djdjd£10€10
I get back:
1500,0000.djdjd1010
As you can see, it only removes a single instance of each character. £, $ and € are fine as there is only one of each in the string.
Here is what I have so far:
function validatePriceRange(value, min, max) {
var replacements = ["£", "$", "€", ",", "."];
$.each(replacements, function (index, item) {
value = value.replace(item, "");
});
var value = parseInt(value, 10);
return value >= min && value <= max;
}
jsFiddle
Can anyone spot what I've done wrong?
replace called with a string as first argument does only one replacement, while using a regular expression with flag g replaces all occurrences.
Using a regular expression, you can also avoid looping over an array and do it in one pass :
value = value.replace(/£|\$|€|,|\./g,'');
You are only cycling through your replacement array once and replace everytime the specific character.
But replace is only replacing the first occurance of a given string.
For a replace all method, look here.
I don't think you need a function for it:
var validated = parseInt('1,500,00.00.$djdjd£10€10'.replace(/[£$€,.]/g,''), 10);
//=> 15000000
// or if you want the validated directly
var validated = function(min,max) {
var v = parseInt('1,500,00.00.$djdjd£10€10'
.replace(/[£$€,.]/g,''), 10);
return v >= min && v <==max;
}(1000, 200000); //=> false
The regular expression should be different if you want to include all digits in the string:
var validated = function(min,max) {
var v = parseInt('1,500,00.00.$djdjd£10€10'
.replace(/[^\d]/g,''), 10);
// ^ replace non numbers
// v now is 150000001010
return v >= min && v <==max;
}(1000, 200000); //=> false
Use a regex with the global flag, which will search and replace all instances
var replacements = ["£", "\\$", "€", ",", "\\."];
$.each(replacements, function (index, item) {
value = value.replace(new RegExp(item, "g"), '');
});
Demo: Fiddle
As already answered here you could use the following regex that replaces all non characters and whitespaces with empty.
var value = "1,500,00.00.$djdjd£10€10"
value = value.replace(/[^\w\s]/gi, '')

i want that the first two characters of my string should not be special characters

I want that the first two characters of my string should not be special characters
function detectInvalidChars(limitField)
{
var len=limitField.value.length;
var char1=limitField.value.substring(0,1);
var char2=limitField.value.substring(1,2);
if(char1=='&'||char1=='<' char1=='!' || char2=='&'||char2=='<'..........so on)
{
alert("Invalid character");
limitField.value = limitField.value.substring(0,len-1);
}
}
instead of matching the char1 and char2 with each special character. What can I do?
You can use a regular expression:
var re = /^([&<!]|.[&<!])/;
if (re.test(limitField.value)) {
alert...
}
look into the string method .charCodeAt(n)
you should be able to then compare the ascii values in ranges.
so for example if you want to exclude control charactercs you could write something like
if (mystring.charCodeAt(0)<32 || mystring.charCodeAt(1)<32) {
alert("Invalid character");
}
or use a regex.
You may find this question helpful:
isalpha replacement for JavaScript?
You can use regex for that on a substring of the original.
substring gets the part of the string from "from" to "to".
/^[0-9a-z]+$/ is regex that allows only 0 ... 9 and a ... z
function is_part_alnum(value, from, to)
substring = value.substring(from, to);
if(!substring.match(/^[0-9a-z]+$/) {
alert("Invalid character(s)");
}
}
If you don't want to use regex and want to define your own set of special characters, you could use a function like this:
function detectInvalidChars(s, count) {
var specialChars = "!##$%^&*()+=-[]\\\';,./{}|\":<>?~_";
var firstChars = s.substr(0, count).split('');
for(var i=0; i<firstChars.length; i++) {
if(specialChars.indexOf(firstChars[i]) !== -1) {
// invalid char detected
}
}
}
Where s is your string and count is the number of the first characters that should be investigated.

startswith in javascript error

I'm using startswith reg exp in Javascript
if ((words).match("^" + string))
but if I enter the characters like , ] [ \ /, Javascript throws an exception.
Any idea?
If you're matching using a regular expression you must make sure you pass a valid Regular Expression to match(). Check the list of special characters to make sure you don't pass an invalid regular expression. The following characters should always be escaped (place a \ before it): [\^$.|?*+()
A better solution would be to use substr() like this:
if( str === words.substr( 0, str.length ) ) {
// match
}
or a solution using indexOf is a (which looks a bit cleaner):
if( 0 === words.indexOf( str ) ) {
// match
}
next you can add a startsWith() method to the string prototype that includes any of the above two solutions to make usage more readable:
String.prototype.startsWith = function(str) {
return ( str === this.substr( 0, str.length ) );
}
When added to the prototype you can use it like this:
words.startsWith( "word" );
One could also use indexOf to determine if the string begins with a fixed value:
str.indexOf(prefix) === 0
If you want to check if a string starts with a fixed value, you could also use substr:
words.substr(0, string.length) === string
If you really want to use regex you have to escape special characters in your string. PHP has a function for it but I don't know any for JavaScript. Try using following function that I found from [Snipplr][1]
function escapeRegEx(str)
{
var specials = new RegExp("[.*+?|()\\[\\]{}\\\\]", "g"); // .*+?|()[]{}\
return str.replace(specials, "\\$&");
}
and use as
var mystring="Some text";
mystring=escapeRegEx(mystring);
If you only need to find strings starting with another string try following
String.prototype.startsWith=function(string) {
return this.indexOf(string) === 0;
}
and use as
var mystring="Some text";
alert(mystring.startsWith("Some"));

How to match with javascript and regex?

I have the following HTML:
<span id="UnitCost5">$3,079.95 to $3,479.95</span>
And i want to use Javascript and Regex to get all number matches.
So i want my script function to return: 3,079.95 AND 3,479.95
Note the text may be different so i need the solution as generic as posible, may be it will be like this:
<span id="UnitCost5">$3,079.95 And Price $3,479.95</span>
All the numbers would be matched by:
\.?\d[\d.,]*
This assumes the numbers you look for can start with a decimal dot. If they cannot, this would work (and maybe produce less false positives):
\d[\d.,]*
Be aware that different local customs exist in number formatting.
I assume that you use appropriate means to get hold of the text value of the HTML nodes you wish to process, and that HTML parsing is not part of the excercise.
You don't want to capture all numbers, otherwise you would get the 5 in the id, too. I would guess, what you're looking for is numbers looking like this: $#,###.##
Here goes the expression for that:
/\$[0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)?/
\$ The dollar sign
[0-9]{1,3} One to three digits
(,[0-9]{3})* [Optional]: Digit triplets, preceded by a comma
(\.[0-9]+)? [Optional]: Even more digits, preceded by a period
/(?:\d{1,3},)*\d{1,3}(?:\.\d+)?/g;
Let's break that into parts for explanations:
(?:\d{1,3},)* - Match any numbers separated by a thousand-divider
\d{1,3} - Match the numbers before the decimal point
(?:.\d+) - Match an arbitrary number of decimals
Flag 'g' - Make a global search to find all matches in the string
You can use it like this:
var regex = /(?:\d{1,3},)*\d{1,3}(?:\.\d+)?/g;
var numbers = "$3,079.95 And Price $3,479.95".match(regex);
// numbers[0] = 3,079.95
// numbers[1] = 3,479.95
A very simple solution is the following one. Note that it will also match some invalid number strings like $..44,.777.
\$[0-9,.]+
(function () {
var reg = /\$([\d\.,]+)\s[\w\W]+\s\$([\d\.,]+)$/;
// this function used to clean inner html
function trim(str) {
var str = str.replace(/^\s\s*/, ''),
ws = /\s/,
i = str.length;
while (ws.test(str.charAt(--i)));
return str.slice(0, i + 1);
}
function getNumbersFromElement(elementId) {
var el = document.getElementById(elementId),
text = trim(el.innerHTML),
firstPrice,
secondPrice,
result;
result = reg.exec(text);
if (result[1] && result[2]) {
// inside this block we have valid prices
firstPrice = result[1];
secondPrice = result[2];
// do whatever you need
return firstPrice + ' AND ' + secondPrice;
} else {
return null; // otherwise
}
}
// usage:
getNumbersFromElement('UnitCost5');
})();
The following will return an array of all prices found in the string
function getPrices(str) {
var reg = /\$([\d,.]+)/g;
var prices =[];
var price;
while((price = reg.exec(str))!=null) {
prices.push(price);
}
return prices;
}
edit: note that the regex itself may return some false positives

Categories

Resources