I need to validate user input of first and last name in the one input box. I have to make sure they only use letters and no other characters and is in uppercase or lowercase ex.. John Smith. I can find a lot of ways to do this using regular expressions, but the task has specifically asked that no regular expressions be used.
Even if someone to point me to where I can find this information myself.
Thanks
Just check each letter to see if it's valid. So you create an array of valid characters, then make sure each character is in that array.
function validate_name(name) {
var alphabet = 'abcdefghijklmnopqrstuvwxyz';
alphabet = alphabet + ' ' + alphabet.toUpperCase();
alphabet = alphabet.split(''); //turn it into an array of letters.
for (i=0; i<name.length; i++) {
if (!~alphabet.indexOf(name.charAt(i)) { //!~ just turns -1 into true
return false;
}
}
return true;
}
I have a feeling that, given the question, it is best to keep the solution simple.
Note this observations:
A string can be indexed like an array and has a length like an array. Thus, a string can be looped like an array.
Strings are lexically ordered. That is, "a" < "b" and "A" < "B" are both true.
String.toLower can translate "A" to "a"
Then we can start a basic C-style approach:
for (var i = 0; i < inp.lenth; i++) {
var ch = inp[ch];
if (ch == " ") .. // is space
if (ch >= "a" && ch <= "z") .. // lowercase English letter
..
Of course, the problem may be more than simply ensuring that the letters are all in { a-z, A-Z, space}. Consider these inputs - are they valid?
"John Doe"
"JohnDoe"
" John "
Related
I hope you are well. So, as you can see, from "a-z" I have made a code to transcript every common letter (from "a" to "z") in some symbols. How can I do it when I want to transcript the letters "th" together in different symbol? I do not want the app to translate the letters "t" and "h" separately BUT together! How can I do that? Thank you so much!!!
var theInput = txtBr.value.toLowerCase();
for (var i = 0; i < theInput.length; i++)
{
var letter = theInput.charAt( i );
if( letter.match(/[a-z\s]/i) ) {
var symbol = map[ letter ];
txtarea.innerHTML += symbol;
}
string.search() will return the position of the substring you are searching for.
let string = "nspoiuthpiifs";
let position = string.search("th"); // will return 6
You could then split the string at that position with string.split(), replace the the "th" with the symbol you desire, then rejoin the string with array.join()
Note: string.search() will return only the position of the first one it finds, so you may want to repeat this method until there are none left.
I have an object with strings properties I want to compare to multiple user inputs using case insensitivity. My goal is to match input strings to object strings to increment the associated value by 1 (if it's a match).
var objArr = [
{"O": 0},
{"foo": 0},
{"faa": 0},
{"A": 0}
];
Everything is working smoothly except for the case insensitivity. The RegExp method I used just looks for one letter instead of the whole word. I'm probably not using the right syntax, but I can't find results on google which explain the /i flag along with a variable.
My closest try was :
var re = new RegExp(b, "i"); //problem here
if (allinputs[i].value.match(re)) { //and here
This code indeed allows case insensitivity but it doesn't look for the whole object property string and stops for letters. For exemple typing "foo" will result in a match to "O" because it contains the letter "O", and the property "O" is before "foo". Accordingly, typing "faa" matches to "faa" and not "A", because "faa" is before "A" in the objects array. Strings that don't exist in my object like "asfo" will still be matched to "O" because of the one common letter.
Is there a way to search for the whole property string with case insensivity using the regExp /i flag ? I want to avoid using .toUpperCase() or .toLowerCase() methods if possible.
Fiddle here : https://jsfiddle.net/Lau1989/b39Luhcu/
Thanks for your help
To check that a regex matches the entire string, you can use the assert beginning character (^) and assert end ($).
For example, hello matches e but not ^e$.
For your code, just prepend ^ to the regex and append $:
var re = new RegExp("^" + b + "$", "i");
fiddle
Edit: Some characters have special meanings in regexes (^, $, \, ., *, etc). If you need to use any of these characters, they should be escaped with a \. To do this, you can use this simple replace:
str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
So, your regex will end up being
new RegExp("^" + b.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&") + "$", "i");
See this question for more about escaping a regex.
You could also just convert the two strings to lowercase and then compare them directly. This will allow you to use special characters as well.
if (stringA.toLowerCase() == stringB.toLowerCase())) {
...
}
Your approach was almost right, but you need limitate your regular expression to avoid an any match using ^ (start of string) and $ (end of string).
Here is a code that I made that may fit to your need:
function process()
{
var allinputs = document.querySelectorAll('input[type="text"]');
var list = new Array();
var input = "";
objArr.map(function(value, index, array){ list.push(Object.keys(value))})
for(var i = 0; i < allinputs.length; i++)
{
input = allinputs[i];
if(input.value)
{
list.map(function( item, index, array ) {
var re = new RegExp("^"+input.value+"$", "i");
if(item.toString().match(re))
{
allinputs[i].value = "1";
objArr[index][item] += 1;
allinputs[i].style.backgroundColor = "lime";
document.getElementById('output').innerHTML += item + " : " + objArr[index][item] + "<br />";
}
});
}
}
}
The first thing here is create a list of keys from your objArr, so we can access the key names easily to match with what you type
objArr.map(function(value, index, array){ list.push(Object.keys(value))})
Then the logic stills the same as you already did, a for loop in all inputs. The difference is that the match will occur on list array instead of the objArr. As the index sequence of list and objArr are the same, it's possible to access the object value to increment.
I used the .map() function in the list array, bit it's also possible use a for loop if you prefer, both method will work.
I hope this help you!
code for detecting repeating letter in a string.
var str="paraven4sr";
var hasDuplicates = (/([a-zA-Z])\1+$/).test(str)
alert("repeating string "+hasDuplicates);
I am getting "false" as output for the above string "paraven4sr". But this code works correctly for the strings like "paraaven4sr". i mean if the character repeated consecutively, code gives output as "TRUE". how to rewrite this code so that i ll get output as "TRUE" when the character repeats in a string
JSFIDDLE
var str="paraven4sr";
var hasDuplicates = (/([a-zA-Z]).*?\1/).test(str)
alert("repeating string "+hasDuplicates);
The regular expression /([a-zA-Z])\1+$/ is looking for:
([a-zA-Z]]) - A letter which it captures in the first group; then
\1+ - immediately following it one or more copies of that letter; then
$ - the end of the string.
Changing it to /([a-zA-Z]).*?\1/ instead searches for:
([a-zA-Z]) - A letter which it captures in the first group; then
.*? - zero or more characters (the ? denotes as few as possible); until
\1 - it finds a repeat of the first matched character.
If you have a requirement that the second match must be at the end-of-the-string then you can add $ to the end of the regular expression but from your text description of what you wanted then this did not seem to be necessary.
Try this:
var str = "paraven4sr";
function checkDuplicate(str){
for(var i = 0; i < str.length; i++){
var re = new RegExp("[^"+ str[i] +"]","g");
if(str.replace(re, "").length >= 2){
return true;
}
}
return false;
}
alert(checkDuplicate(str));
Here is jsfiddle
To just test duplicate alphanumeric character (including underscore _):
console.log(/(\w)\1+/.test('aab'));
Something like this?
String.prototype.count=function(s1) {
return (this.length - this.replace(new RegExp(s1,"g"), '').length) / s1.length;
}
"aab".count("a") > 1
EDIT: Sorry, just read that you are not searching for a function to find whether a letter is found more than once but to find whether a letter is a duplicate. Anyway, I leave this function here, maybe it can help. Sorry ;)
My string has [1212,1212],[1212,11212],...
I'd like to extract each value into an array for example I'd want 1212,1212 as one pair and evaluate a series of steps.
Tried /[[0-9],[0-9]]/ but It wasn't doing the task as I wanted. Basically I'm a noob in Regex, could someone please help.
Thanks in advance
You need some modifications for your regular expression for it to work correctly:
/\[[0-9]+,[0-9]+\]/g
You need to escape square brackets [ because they have special meaning.
[0-9] matches only one digits, you need the + quantifier to match one or more digits and thus [0-9]+.
Use the global modifier g to extract all matches.
Then you can extract all the values into an array like this:
var input = "[1212,1212],[1212,11212]";
var pattern = /\[[0-9]+,[0-9]+\]/g;
var result = [];
var currentMatch;
while((currentMatch = pattern.exec(input)) != null) {
result.push(currentMatch.toString());
}
result;
Or if you don't need to find the matches successively one at a time, then you can use String.match() as #Matthew Mcveigh did:
var input = "[1212,1212],[1212,11212]";
var result = input.match(/\[[0-9]+,[0-9]+\]/g);
It seems like you just need to match one or more digits before and after a comma, so you could do the following:
"[1212,1212],[1212,11212]".match(/\d+,\d+/g)
Which will give you the array: ["1212,1212", "1212,11212"]
To extract the pairs:
var result = "[1212,1212],[1212,11212]".match(/\d+,\d+/g);
for (var i = 0; i < result.length; i++) {
var pair = result[i].match(/\d+/g),
left = pair[0], right = pair[1];
alert("left: " + left + ", right: " + right);
}
You need to escape the literal brackets that you want to match. You can also use \d to match "any digit", which makes it tidier. Also, you're only matching one digit. You need to match "one or more" (+ quantifier)
/\[\d+,\d+\]/g
That g modifier finds all matches in the string, otherwise only the first one is found.
Given a set of words, I need to put them in an hash keyed on the first letter of the word.
I have words = {}, with keys A..Z and 0 for numbers and symbols.
I was doing something like
var firstLetter = name.charAt(0);
firstLetter = firstLetter.toUpperCase();
if (firstLetter < "A" || firstLetter > "Z") {
firstLetter = "0";
}
if (words[firstLetter] === undefined) {
words[firstLetter] = [];
}
words[firstLetter].push(name);
but this fails with dieresis and other chars, like in the word Ärzteversorgung.
That word is put in the "0" array, how could I put it in the "A" array?
You can use this to test if a character is likely to be a letter:
var firstLetter = name.charAt(0).toUpperCase();
if( firstLetter.toLowerCase() != firstLetter) {
// it's a letter
}
else {
// it's a symbol
}
This works because JavaScript already has a mapping for lowercase to uppercase letters (and vice versa), so if a character is unchanged by toLowerCase() then it's not in the letter table.
Try converting the character to its uppercase and lowercase and check to see if there's a difference. Only letter characters change when they are converted to their respective upper and lower case (numbers, punctuation marks, etc. don't). Below is a sample function using this concept in mind:
function isALetter(charVal)
{
if( charVal.toUpperCase() != charVal.toLowerCase() )
return true;
else
return false;
}
You could use a regular expression. Unfortunately, JavaScript does not consider international characters to be "word characters". But you can do it with the regular expression below:
var firstLetter = name.charAt(0);
firstLetter = firstLetter.toUpperCase();
if (!firstLetter.match(/^\wÀÈÌÒÙàèìòùÁÉÍÓÚÝáéíóúýÂÊÎÔÛâêîôûÃÑÕãñõÄËÏÖÜäëïöüçÇßØøÅåÆæÞþÐð$/)) {
firstLetter = "0";
}
if (words[firstLetter] === undefined) {
words[firstLetter] = [];
}
words[firstLetter].push(name);
You can use .charCodeAt(0); to get the position in the ASCII Chart and then do some checks.
The ranges you are looking for are probably 65-90, 97-122, 128-154, 160-165 (inclusive), but double check this by viewing the ASCII Chart
Something like this
if((x>64&&x<91)||(x>96&&x<123)||(x>127&&x<155)||(x>159&&x<166))
Where x is the Char Code
This is fortunately now possible without external libraries. Straight from the docs:
let story = "It’s the Cheshire Cat: now I shall have somebody to talk to.";
// Most explicit form
story.match(/\p{General_Category=Letter}/gu);
// It is not mandatory to use the property name for General categories
story.match(/\p{Letter}/gu);