RegEx which tests if sentence contain every letter from polish alphabet - javascript

function isPangram(sentence) {
const polishSpecial = /[śćóźąęłżń]/;
const RegEx = /(\w).*\1/;
return !RegEx.test(sentence);
}
Mine regular expression only checks whether the letter is repeating itself. I want also add these polish special characters to the main RegEx.
The point is that sentence can only have one letter from [a-z] and [śćóźąęłżń], then it's true. If sentence doesn't have even one letter from [a-z] or [śćóźąęłżń], then it's false.

You can use
const ContainsAllPolishLetters = (str) =>
{
return [...new Set(str.match(/[A-Za-zżźćńółęąśŻŹĆĄŚĘŁÓŃ]/g))].length == 64;
}
console.log(ContainsAllPolishLetters("...AaĄąBbCcĆćDdEeĘęFfGgHhIiJjKkLlŁłMmNnŃńOoÓóPpRrSsŚśTtUuWwYyZzŹźŻż..."));
console.log(ContainsAllPolishLetters("...A tu mamy za mało polskich liter..."));
Details:
.match(/[A-Za-zżźćńółęąśŻŹĆĄŚĘŁÓŃ]/g - extracts all Polish letters from a str string
[...new Set(<result_of_Step_1>)] - removes duplicate letters from the array
<result_of_the_above>.length == 64 - checks if the count of unique letters is equal to 64, 32 lower- and 32 uppercase Polish letter count. If yes, the return value is true, otherwise, false.

Related

How to check is string has both letter and number in javascript

I have string "JHJK34GHJ456HJK". How to check if this string has both letter and number, doesn't have whitespace, doesn't have special characters like # - /, If has only letter or only number didn't match.
I try with regex below, result is true if string is only number or letter.
const queryLetterNumber = /^[A-Za-z0-9]*$/.test("JHJK34GHJ456HJK");
const input= [
'JHJK34GHJ456HJK',
'JHJKAAGHJAAAHJK',
'123456789012345',
'JHJK34 space JK',
'JHJK34$dollarJK'
];
const regex = /^(?=.*[0-9])(?=.*[A-Za-z])[A-Za-z0-9]+$/;
input.forEach(str => {
console.log(str + ' => ' + regex.test(str));
});
Output:
JHJK34GHJ456HJK => true
JHJKAAGHJAAAHJK => false
123456789012345 => false
JHJK34 space JK => false
JHJK34$dollarJK => false
Explanation:
^ - anchor at beginning
(?=.*[0-9]) - positive lookahead expecting at least one digit
(?=.*[A-Za-z]) - positive lookahead expecting at least one alpha char
[A-Za-z0-9]+ - expect 1+ alphanumeric chars
$ - anchor at end
you should use a regular expression to check for alphanumeric content in the string
/^[a-z0-9]+$/i
The above is a sample that checks for a-z and numbers from 0-9. however, review other options as given here

Regex to check for 3 same letters in a string?

I need to create regex which will look for 3 same letters in a string, regardless of the order.
Example:
'aa2ff333' -> false
'aa2a' -> true
'aaa2' -> true
I tried this but it check for consecutive letters:
(.)\1\1
Any advice?
You may use this regex with lookahead:
/([a-zA-Z])(?=(?:.*?\1){2})/
RegEx Demo
RegEx Details:
([a-zA-Z]): Match a letter [a-zA-Z] and capture it in group #1
(?=: Start lookahead
(?:.*?\1){2}: That has at least 2 occurrences of same character as in capture group #1. .*?\1 Matches back-reference \1 after 0 or more of any character. This allows matching repetitions anywhere in input.
): End lookahead
One way is to loop through the string and count occurrence of each character then check if any of character appears for exact three times
let threeChars = (str) => {
let obj = [...str].reduce((op, inp) => {
if (/[a-z]/i.test(inp)) {
op[inp] = op[inp] || 0
op[inp] += 1
}
return op
}, {})
return Object.values(obj).some(v => v === 3)
}
console.log(threeChars('aa2ff333'))
console.log(threeChars('aa2a'))
console.log(threeChars('aaa2'))
P.S:-
You can make it case insensitive by removing the i flag
In case you need to at least 3 character you can change v == 3 to v >= 3

Regex for min 8 characters, one uppercase letter and min one number not on the beginning and the end of the string

This is the description:
must be at least 8 characters long
string must contain at least one uppercase letter
the number must divide the string into at least two character strings
Examples:
Bad strings: asdFghjk, 123aSdfghjk, asd6H
Matching string: asd3fGhjk
So far I got this:
^(?!(0-9))(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$(?!(0-9))
You can check the length of string manually and then
^(?=.*[A-Z])(?:[a-zA-Z]+?\d+[a-zA-Z]+?)+$
let arr = ['asdFghjk','123aSdfghjk','asd6H','asd3fGhjk','aAs2323ASDdncnc','a1a1a1a1a1A','dgd3323hdhdh132asas']
let tester = (str) =>{
return str.length > 7 && /^(?=.*[A-Z])(?:[a-zA-Z]+?\d+[a-zA-Z]+?)+$/.test(str)
}
arr.forEach(str=>{
console.log(str, ' --> ',tester(str))
})

Regular Expression to provided max 2 spaces

I have to write a regular expression in JavaScript which will satisfy the below
a) accept only alphabetic characters(small/caps)
b) should not exceed beyond 20 characters
c) max 2 spaces can be provided.
Valid test cases
a) Name
b) name
c) namea nameb
d) namea nameb namecd
e) namea nameb (2 consecutive spaces is also valid but total number of spaces cannot be more than 2)
My attempt (but not working)
function test(){
var originalString="abc rt t tt";
var myRegEx = /^([a-zA-Z ]{1,20})+$/;
var isValid = myRegEx.test(originalString);
alert(isValid);
}
What is the mistake and how to fix?
The regex /^([a-zA-Z ]{1,20})+$/ will match one to twenty alphabet and/or space one or more times. So, basically this allows alphabets and spaces in any sequence any number of times.
You can use
^[a-zA-Z]+(\s[a-zA-Z]*){0,2}$
Demo
var regex = /^[a-zA-Z]+(\s[a-zA-Z]*){0,2}$/;
var result = document.getElementById('result');
document.getElementById('text').addEventListener('keyup', function(e) {
var value = this.value;
var isValid = value.length <= 20 && regex.test(value);
result.innerHTML = isValid ? 'Valid' : 'InValid';
result.className = isValid ? 'valid' : 'invalid';
}, false);
input:valid, .valid {
color: green;
}
input:invalid, .invalid {
color: red;
}
<input id="text" pattern="[a-zA-Z]+(\s[a-zA-Z]*){0,2}" maxlength="20" />
<div id="result"></div>
Explanation:
[a-zA-Z]+ Match alphabets one or more times
\s: Matches a space character
{0,2}: Match previous class zero to two times.
To check if the string does not exceed 20 characters, String.length property can be used.
if (str.length <= 20 && regex.test(str)) {
// Valid
} else {
// Invalid
}
You can check that the input contains only letters, with a maximum of two internal spaces, as follows:
/^[a-z]+ ?[a-z]* ?[a-z]+$/i
In other words, starting at the beginning, match a sequence of one of more letters, then maybe a space, then a possibly empty bunch of letters, then maybe a space again, then finally a sequence of one or more letters taking you to the end.
To check the length, without having to check it using JS, add a look-ahead:
/^(?=.{1,20}$)[a-z]+ ?[a-z]* ?[a-z]+$/i
^^^^^^^^^^^^ LOOK-AHEAD TO LIMIT CHARS TO 20
This says, "look ahead and find between one and twenty characters up to the end of the string".

Filter non-alpha-numeric and make titlecase

I have a list with a bunch of names which I need to turn into alphanumeric usernames. What I would like to do is take the name, remove any non-alpha numeric values and turn it into title case where characters were removed. For example:
johnson -> Johnson
Van Halen -> VanHalen
Torres-hernandez -> TorresHernandez
Rafael van der vaart -> RafaelVanDerVaart
Can this be done with a regular expression?
Using some string manipulation, you can do this fairly simply.
var name = "Torres-hernandez", i, part, out = "";
parts = name.split(/[^a-z0-9]+/gi);
for (i=0; part = parts[i++];) {
out += part[0].toUpperCase() + part.slice(1).toLowerCase();
}
var names = [
'johnson',
'Van Halen',
'Torres-hernandez',
'Rafael van der vaart'
]
for (var i = 0; i < names.length; i++) {
names[i] = names[i].replace(/(\W|^)(\w)/g, function(match) {
return match.substr(-1).toUpperCase();
});
}
console.log(names);
prints
[ 'Johnson', 'VanHalen', 'TorresHernandez', 'RafaelVanDerVaart' ]
You can do it with simple regexp:
var titleCase = function(s) {
return s.toLowerCase().replace(/(?:^|\W)+(\w|$)/g, function(match, tail) {
return tail.toUpperCase();
});
};
Regular expression /(?:^|\W)+(\w|$)/g here catches substrings from the begining of the previous word to the first letter of the new one which should be capitalized.
It captures the whole match and replaces it with the uppercased last character tail.
If your string ends with bad characters (e.g. whitespaces) then it'll be captured too, but taild in this case will be an empty string:
' toRReS $##%^! heRnAndeZ -++--=-=' -> 'TorresHernandez'
Let's examine my regexp:
(^|\W)+ - the sequence (...)+ of non-alphanumeric characters \W or the start of the string ^ which may be followed by any number of non-alphanumeric characters. It should contain at leas one character unless it's the start of the string, it which case it may be empty.
(?:^|\W)+ - same thing, but it won't be cached because of ?:. We don't really care about this part and just want to strip it.
(\w|$) - any alphanumeric characters \w or the end of the string $. This part will be cached and placed into tail variable.
Update If regular expressions confuses you, you may do the same thing with string and array operations:
var titleCase = function(str) {
return str.split(/\W+/g)
.filter(function(s) {
return s.length > 0;
}).map(function(s) {
return s[0].toUpperCase() + s.slice(1).toLowerCase();
}).join('');
};
This solution was inspired by FakeRainBrigand's answer and is very similar to his own. The difference is that my version uses array operations instead of for loop and uses filter to handle strings with bad character at the beginning or at the and of it.
I used \w and \W special literals in my regular expressions which are equal to [A-Za-z0-9_] and [^A-Za-z0-9_] respectively (see JavaScript Regular Expressions Docs). If you don't want _ to be counted as an alphanumeric character you should replace \w and \W with exact character sets to be matched (e.g. [A-Za-z0-9] and [^A-Za-z0-9]).

Categories

Resources