Extract proper username from a string with regex in js - javascript

I want to extract a username from a string that user has typed into input. The thing is that I don't want just simply validate username, but I want to show for user what will be the final username even if user types any non-allowed characters.
So for example if user types in something like &%$User)(Nam-e it will show usernam-e
there is similar question with answer Regular expression to validate username, but somehow it gives me an error of Invalid group on node.js when I try to use it with a match or exec functions.
Anyway, most of the examples online only validates the username against regex, but not actually provides the outcome of the appropriate username.
Rules are following:
Only contains alphanumeric characters, underscore, dash and dot.
Underscore, dash and dot can't be at the end or start of a username
(e.g _username / username_).
Underscore, dash and dot can't be next to each other (e.g
user_-.name).
Underscore, dash or dot can't be used multiple times in a row (e.g
user__name).
So far I was only capable to do something similar with using replace function number of times
value.replace(/[^\w-]*/g,'').replace(/^[^a-z]*/,'').replace(/-{2,}/g,'-').replace(/_{2,}/g,'_');
But this doesn't look like an efficient code, especially that I would actually need to add even more replace functions to extract appropriate username.
Any ideas how to achieve that?

Assumes that you want the name displayed in lower-case, as in your example:
function user( n ) {
var name = n.replace( /^[^a-z]+|[^a-z\d_\-.]|[_\-.](?![a-z\d])/gi, '' );
if ( n != name ) {
console.log( 'Username invalid' );
}
return name.toLowerCase();
}
user('&%$User)(Nam-e'); // Username invalid, usernam-e
user('_Giedrius_one_'); // Username invalid, giedrius_one
user('Giedrius--one'); // Username invalid, giedrius-one
user('Giedrius-one'); // giedrius-one
user('/.bob_/'); // Username invalid, bob

Related

Validating name in visual studio code

var userName = input.question('Please enter your name: '); //Asking User to enter their Name.
while (userName.includes('.')) {
console.log ("Invalid Name!");
var userName = input.question('Please enter your name: '); //Asking User to enter their Name.
}
Above code will ask the user his/her name and store it in "userName". Then it will validate using .includes to check unwanted characters and numbers.
I want to validate if userName has numbers or unwanted characters such as "?/.,;'[]{}|&^%#" etc. I have tried using .includes and validate if a name has "." However, I'm not sure how to go about from there to validate the rest.
After the while checks that it contains the unwanted characters, it will re-prompt the user to enter a new name and it will check again until it returns false.
Is there a solution to this?
You can use REGEX to search for non-alphabetic or space characters in the string:
userName.search(/^[a-zA-Z\s]+$/)
The response will be 0 or -1. 0 means that no characters except A-Z, a-z and space were found, -1 means the contrary.
Edit: I found similar question with more detailed answers here.
let chars = /[$&+,:;=?##|'<>.^*()%!-]/g;
chars.test(UserName)
Use Regular expressions ( Regex )
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions

Regex to extract arguments passed into string '#substr( , , )'

we have a text input where the user can enter some text and apply some functions on top of the text like ( substr , replace ) etc. For example user can enter the text "hello" in the text input and can apply the substring function ( #substr(hello, 'startIndex', 'length'))and can mention the start index and the length etc.
Need to use the regex to extract the values passed into the #substr function for validating the mandatory fields. For example 'start index' and 'length' is required when the user selects the substr function.
Below are the different scenarios and its expected output .
#substr(hello,1,3) ---> ['hello','1','3']
#substr($(sometext),1,3) ---> ['$(sometext)','1','3']
#substr(#trim(hello),1,3) ----> ['#trim(hello)','1','3']
#substr(#replace(hello-world,hello,hi),1,3) ---> ['#replace(hello-world,hello,hi)','1','3']
As from the above examples need to extract the arguments passed into the #substr function as array elements.
Tried this regex
/#substr\((.*?),(.*?),(.*?)\)/g
This fails when we have a nested functions like this - #substr(#replace(hello-world,hello,hi),1,3)
You could use the below regex with capturing groups.
#(\S+?)\((.*)\,(\d+),(\d+)\)
For nested matching, it is not impossible, but much complex in regex. The easy approach should be avoiding regex and using js code for nested matching.
This regex can solve your problems, if the string takes up an entire line, but if you enter comma commands in the second argument, it will fail, this is a very complex problem to solve with simple regex. I think you're knocking on the compilers' door.
regex = /^#substr\((.*),(.*),(.*)\)$/;
text = "#substr(#replace(hello-world,hello,hi),1,3)";
console.log(regex.exec(text));
If you're trying to get the length of user input or index, you could put all the desired methods inside a function or multiple functions that call be called on button-click.
https://www.bitdegree.org/learn/javascript-input
I may be misunderstanding but if I take one of your examples:
#substr(hello,1,3) ---> ['hello','1','3']
When I run
str = "hello world"
str.substring(1,3) --> I get "el" (not "hello", "1", "3")
Get some text:
var firstName = document.getElementById("firstName").value;
var age = document.getElementById("age").value;
Click a button to call your function.
function doSubstringStuff(textValue, subString_mode) {
if subString_mode == "length" {
return textValue.length;
}
OR
Validate the length matches your criteria.
if (textValue.length > 10) {
alert("The name must have no more than 10 characters");
Or Perform other tasks, determined by the argument "mode"
else if subString_mode == "integer_test"{
if (isNaN(textValue) || age < 12 || age > 100){alert("The age must be between numbers 12 and 100")};

Validation to check if the user has entered the correct format

I have a dynamic grid that has a numeric field in which I have applied masking. Also it has a plus button means the user can add many rows as he wants. The masking is applied like this:
<input type='textbox' placeholder='00000-00-000' data-mask='00000-00-000'
This masking is applied when the user enters 10 digit number but it lets the user enter a 2 or 3 digit number as well. For this I am trying to apply validation while saving so that it checks whether the value entered matches the required format.
What I have done so far is :
value = $(this).find('td:eq(1)').find('input').val(); //saves the entered value in a variable value
myRegExp = new RegExp(/\d{5}-\d{2}-\d{3}/);
if (!myRegExp.test(value)) {
valid = false;
}
else
valid = true;
The value that user enters is saved in varaible called value and then I have defined my Regex Expression to match my value with that expression but somehow this regex expression is not working. Is this the correct way to define regex expression? What am I missing here? My required format is 00000-00-000. Any help would be appreciated.
Your logic is correct but you have not defined the end point that's why it allows to insert more values.
In your Regex it only checks if the 10 digits are in the specific order
try out this
myRegExp = new RegExp(/^\d{5}-\d{2}-\d{3}$/);

Regex to match only certain characters or strings and only one instance of each?

I feel like I know just enough about Regexes to get stuck. That said, I have an input field which will allow users to enter their currency symbol. I'm only wanting to allow said currency symbol and disallow anything else from being entered into that field. Some countries don't actually have a single symbol, but are just two or three characters, e.g., "Kr" for Krona. So the field has a max length of 3. Given it needs a max length of three to accommodate some currencies, I also don't want to allow three dollar signs to be entered, e.g., "$$$". I would only want to allow one single dollar, pound, euro, etc. sign.
Here's my basic code for allowing only these symbos in the input:
$('#id_currency_symbol').on('input',function (){
var value = $(this).val().toString();
newvalue = value.replace(/[^$£€¥₣₩₩¥₽₺₹Rkr]+/g,'');
$(this).val(newvalue);
});
This works for only allowing these symbols/letters, but like I said above, I don't want to allow users to enter more than a single instance of some symbols, i.e. dollar sign ($). In addition, I want to match exact strings for cases where the "symbol" is actually just two or three characters. In the case of Krona, the "symbol" is Kr. Given the above, users could in theory enter "rK" and it would be perfectly valid according to the regex, but I would ONLY want to allow the exact match of "Kr." Is that possible?
Thanks
I would suggest to forget regex, and go for O(1) algos,
var allowedCurrencyCodes = {
"$":true,
"¢":true,
"£":true,
"INR":true,
"Kr":true,
.....,
.....,
.....
}
$(this).val(allowedCurrencyCodes[$(this).val()]?$(this).val():"");
you need to perform the check at blur event or when user has entered at least 3 chars, else it becomes buggy as it will keep on wiping the data right after first char.
if you want to keep check real time i.e. responsive when user is typing in, then you need to change the structure of allowedCurrencyCodes and convert it to nested object for multi-char currency codes, e.g $,£ would be exactly same but INR or Kr will be defined like
"I":{
"N":{
"R":true
}
},
"K":{
"r":true
}
and minor change in fetch logic will be applied, where you will capture input and split it in array and then dip in allowedCurrencyCodes based on input chars, like
allowedCurrencyCodes[inputChar[0]][inputChar[1]]
or
allowedCurrencyCodes[inputChar[0]][inputChar[1]][inputChar[2]]
You may find the first occurrence of a currency symbol or acronym using a regex and then replace the whole input with the matched string. Single character currencies can be listed in [...] and any longer string may be added by alternation:
var checkInput = function(input) {
var regex = /[$£€¥₣₩₩¥₽₺₹]|kr/i;
input = regex.exec(input);
return input == null ? "" : input[0];
}
console.log(checkInput("lkjahfkdshfjsdf Kr asdasda"));
console.log(checkInput("kr"));
console.log(checkInput("rk"));
console.log(checkInput("$$$"));
console.log(checkInput("₣₩₩"));
console.log(checkInput("ABC"));
For completeness:
The "Regex to match only certain characters or strings and only one instance of each":
^(?:[$£€¥₣₩₩¥₽₺₹]|kr)$
Demo: https://regex101.com/r/w9p9d9/1
Regex to strip off anything but "certain characters or strings" and these characters too if they appear more than once (for use within newvalue = value.replace(...,'');):
^(?=.*?([$£€¥₣₩₩¥₽₺₹]|kr)|).*
Demo: https://regex101.com/r/qocsv5/1

regexp - first and last name javaScript

I'm trying to make a JavaScript regexp such as the facebook uses for real names:
Names can’t include:
Symbols
numbers
unusual capitalization
repeating characters or punctuation
source: Facebook help center
Here is my regexp:
/^[a-z \,\.\'\-]+$/i
The problem with this regexp is that it doesn't check for repeated characters or punctuation:
then I found this :
/(.)\1/
so I'm now checking it like this:
$('input [type=text]).keyup(function(){
var name = $(this).val();
var myregex = /^[a-z\,\.\'\-]+$/i
var duplicate = /(.)\1/
if(name != myregex.exec(name) || name == /(.)\1/)
{// the name entered is wrong
}
else
//the name is ok
but the problem I'm facing is with inputs like:
Moore
Callie
Maggie
what can I do to get the problem solved?
You should stop trying to solve this problem:
It is very complicated
Names are very personal
For instance your system will never be able to validate names from China
or Japan.... (For instance: Børre Ørevål ,汉/漢 )
So just leave the whole idea, and let people freely enter their names with no restrictions.
Related: Regular expression for validating names and surnames?

Categories

Resources