Regular expression match in javascript on a list of items - javascript

How to check in javascript if my string contains any of the characters ~ and ’.
Is there a way to achieve this using regular expression match test, rather than writing a for loop to check if my string contains any of there characters using indexOf()

regex.test(str); is the thing you want to check. It looks in str if it is mathing regex, true if it does, else false
var a = "hey";
var b = "h~y";
var c = "he’";
var reg = /[’~]/ ;
console.log(reg.test(a)); // false
console.log(reg.test(b)); // true
console.log(reg.test(c)) // true

Just try to find given string using indexOf() it will return value greater than -1. If value is 0,1 or any number then true else false.
var string = "Some Text'";
if (string.indexOf("~") > -1 || string.indexOf("'") > -1)
{
console.log("contains");
}else{
console.log("not contains");
}

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(','));
}

Trouble with Javascript easy coderbyte challenge

I'm attempting to answer this question:
Using the JavaScript language, have the function SimpleSymbols(str) take the str parameter being passed and determine if it is an acceptable sequence by either returning the string true or false. The str parameter will be composed of + and = symbols with several letters between them (ie. ++d+===+c++==a) and for the string to be true each letter must be surrounded by a + symbol. So the string to the left would be false. The string will not be empty and will have at least one letter.
Here's my solution:
function SimpleSymbols(str) {
var test;
for (var i =0; i<str.length; i++){
if ((str.charAt(i)!== '+' && str.charAt(i+1) === str.match(/[a-z]/))
||(str.charAt(i+1) === str.match(/[a-z]/) && str.charAt(i+2) !== '+')){
test = false;
break;
}
else if (str.charAt(0) === str.match(/[a-z]/)){
test = false;
break;}
else {
test= true;}
}
return test;
};
I think you can just use two regex and then compare the length of arrays returned by them
function SimpleSymbols(str){
return str.match(/[a-z]/g).length == str.match(/\+[a-z]\+/g).length;
}
The first regex /[a-z]/g will match all the letters and /\+[a-z]\+/g will match all the letters which are followed and preceded by a literal +.
Then, we just use the Array.length property to check if the lengths are same or not and then return the Boolean result. As simple as that.

traverse a string char by char javascript

function SimpleSymbols(str) {
var letter =['a','b','c','d','e','f','g','h','i','j',
'k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
var newstr = "";
for (var i = 0; i<str.length; i++){
if (str.charAt(i).toLowerCase() in letter){
newstr += "M";
}
else{
newstr += "X";
}
}
return newstr;
}
If str is "Argument goes here" it returns XXXXXXXXX. WHy doesn't it return MMMMMMMMMM?
you do not look up an entry in an array with in. use indexOf() to find the position of an array entry. indexOf() will return the position or -1 if no entry is found.
for (var i = 0; i<str.length; i++){
var strChar = str.charAt(i).toLowerCase();
if ( letter.indexOf(strChar) >= 0 ) {
newstr += "M";
}
…
The in operator returns true if the object has a property with that name, not with that value.
An array is basically an object with numeric properties. I.e. the indexes are the property names of the object. It basically looks like this:
var letters = {
0: 'a',
1: 'b',
...
length: ...
};
So in your case the condition will only be true if str.charAt(i).toLowerCase() returns a number between 0 and letter.length (and since charAt only returns one character, it can only be 0-9).
Example:
> var letters = ['a', 'b', 'c'];
> 'a' in letters // array doesn't have a property 'a'
false
> 0 in letters // array has a property 0 (it's the first element)
true
So since, "Argument goes here" doesn't contain any digits, the in condition will always be false and that's why you get XXXXXX... as result.
See the question "How do I check if an array includes an object in JavaScript?" for testing the existence of an element in an array.
FWIW, to make the in operator work, you would have to create an object of the form:
var letters = {
'a': true,
'b': true,
// ...
};
but that's a bit cumbersome to write.
Allow me to offer a side view, another way handle what I think you intent to do by using Regular Expressions with something like:
"test2".replace(/[a-z]/gi,"M").replace(/[^M]/g,"X") //Outputs "MMMMX"
String.replace will replace an string that contains letters from [a-z] the i at the end of the expression means case insensitive. g means will search for all possible matches and not just the first match. In the second expression [^M] this ^ means negation so anything that is not an M will be replaced with X.
There is another way in which we implement a custom function within the String.replace using Regular Expressions and it can be implemented like this:
"test2".replace(/([a-z])|([^a-z])/gi,
function(m,g1, g2){
return g1 ? "M" : "X";
});
In regular expression parenthesis creates groups and | means or in this expression ([a-z])|([^a-z]) there 2 groups one with letters from a-z and the other which means everything that is not a-z with the replace function we asked only for group g1 if it is group 1 is M otherwise is an X.
Another cool thing you could do is add this function to all your string by prototyping it like:
String.prototype.traverse = function(){ return this.replace(/([a-z])|([^a-z])/gi,function(m,g1){ return g1 ? "M" : "X" });}
Then it can be used as simple as: "test1".traverse();

Find multiple fragments of string in a string

I have a string of IDs in CSV format in an input box
12,23,26,32
I have to check if this string contains 23 or 24, if yes then return false, else return true
Use indexOf. You can check if it contains a subString. If not found, it returns -1
var str = "12,23,26,32"
return !(str.indexOf("23")!=-1 || str.indexOf("24")!=-1) // Dont have 23 or 24
=======EDIT=======
Like #Matt said in comment, this solution will work also to "12,239,26,32" and thats not the point.
Make the split before check the indexOf, then you will get the element between the commas.
var array = "12,23,26,32".split(",");
return !(array.indexOf("23")!=-1 || array.indexOf("24")!=-1) // Dont have 23 or 24
!/(^|,)2[34](,|$)/.test( str );
or if there may be whitespace present
!/(^|,)\s*2[34]\s*(,|$)/.test( str );
The RegExp test method returns true if the string argument matches the regular expression or false if it doesn't. The ! inverts the result of the test call.
^ is the metacharacter for the start of the string, so(^|,) means either 'at the start of the string' or 'one comma character'.
It can't be written [^,] as that would mean 'one character that isn't a comma', and it can't be written [,^] as that means 'one character that is either a comma or a literal ^ character.
2[34] means 2 followed by 3 or 4.
(,|$) means a comma or the end $ of the string.
\s* means zero or more space characters.
if (/(?:^|,)(23|24)(?:,|$)/.test("12,23,26,32")) {
/* found 23 or 24 */
}
Try this
var str = "12,23,26,32";
var isFound = (str.indexOf('23') || str.indexOf('24')) > -1;
var str = "12,23,26,32";
var obj = str.split(",");
var isFound = false;
for(i=0; i < obj.length; i++)
{
if(obj[i] == "23" || obj[i] == "24")
{
isFound = true;
break;
}
}
return isFound;

jQuery - check whether string contains numeric value

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

Categories

Resources