I have feature to add wesbsite option in form.
Here user can write domain /url and this domain/url can be in English as well Japanese language as below.
www.google.com
www.南极星.com
I am using following validation for english domains
for (var j = 0; j < dname.length; j++) {
var dh = dname.charAt(j);
var hh = dh.charCodeAt(0);
/*if(dh!='.'){
var chkip=chkip+dh;
}*/
if ((hh > 47 && hh < 59) || (hh > 64 && hh < 91) || (hh > 96 && hh < 123) || hh == 45 || hh == 46) {
var index2 = dname.indexOf('www.');
if (index2 != -1) {
dname = dname.substring(index2 + 4);
if (dname.charAt(0) == '-') {
error_msg = '\'-\'' + window.gt.gettext('not_allowed_in_beginning');
return error_msg;
}
}
if ((j == 0 || j == dname.length - 1) && hh == 45) {
//if(hh == 45){
error_msg = '\'-\'' + window.gt.gettext('not_allowed_in_beginning');
}
} else {
error_msg = window.gt.gettext('cmnscrpt_domname_inval');
}
}
what can I write to validate Japanese domain ?
I think you should use form validator. For example, I prefer to use this one: http://jqueryvalidation.org/validate. You can write your own validation rules depending on language.
For exanple, this is how you can validate car VIN number:
(function() {
jQuery.validator.addMethod("vin", function(value, element) {
return this.optional(element) || /^[a-z0-9]{17}$/i.test(value);
}, "");
})();
There is a very simple method to apply all you RegEx logic(that one can apply easily in English) for any Language using Unicode.
For matching a range of Unicode Characters like all Alphabets [A-Za-z] we can use
[\u0041-\u005A] where \u0041 is Hex-Code for A and \u005A is Hex Code for Z
'matchCAPS leTTer'.match(/[\u0041-\u005A]+/g)
//output ["CAPS", "TT"]
In the same way we can use other Unicode characters or their equivalent Hex-Code according to their Hexadecimal Order (eg: \u0A10 to \u0A1F) provided by unicode.org
Below is a regEx for url validation
url.match(/^(ht|f)tps?:\/\/[a-z0-9-\.]+\.[a-z]{2,4}\/?([^\s<>\#%"\,\{\}\\|\\\^\[\]`]+)?$/)
you just replace a-z, A-Z, 0-9 with the similar characters from Japanese Unicode set and it will work fine. I don't know Japanese :)
Related
I want allow only numbers and letters and this special caracters (# ‘ () + - ? ! / & * ») in JavaScript.
For this moment i have only numbers and letters allow but i want a special caracters. ( # ‘ () + - ? ! / & * » )
$("#test").keypress(function(e) {
$("#error").remove();
var k = e.keyCode,
$return = ((k > 64 && k < 91) || (k > 96 && k < 123) || k == 8 || k == 32 || (k >= 49 && k <= 57));
if(!$return) {
$("<span/>",{
"id" : "error",
"html" : "No special caracters allow !"
}).insertAfter($j(this));
return false;
}
});
Thank you in advance for your fast reply.
It would probably be easier to use e.key instead, which will give you the actual character, and not the character code, and then you can check the character against a regular expression that contains the permitted characters:
const isOk = /[a-z0-9#‘)(+-?!\/&*»]/i.test(e.key);
if (!isOk) {
// handle error
}
You can use a regex:
[a-zA-Z0-9\[#()+-?!&*‘»]*
you can test it on https://regex101.com/r/sxrFqq/2
Simple regex:
/[a-z0-9\#\'\(\)\+\-\/\&\*\»]/gi
I want to do a validate check to see if the SSN entered into a textbox follows this specific format: XXX-XX-XXXX as its being typed
I tried doing a function that just auto formats like this...
function ssnCheck() {
var val = this.value.replace(/\D/g, '');
var newVal = '';
if(val.length > 4) {
this.value = val;
}
if((val.length > 3) && (val.length < 6)) {
newVal += val.substr(0, 3) + '-';
val = val.substr(3);
}
if (val.length > 5) {
newVal += val.substr(0, 3) + '-';
newVal += val.substr(3, 2) + '-';
val = val.substr(5);
}
newVal += val;
this.value = newVal;
}
But it would bug out sometimes and not fully work especially on Mobile devices. I tried the solutions below, but they aren't working. The way I'm applying the above is by doing this..
document.getElementById("ssn").addEventListener('keyup',ssnCheck,false);
Any help on getting it to work so it auto formats as its being typed, or a better solution to this issue since it HAS to show in the XXX-XX-XXXX format when they are done typing in the box.
try this regax:
^\d{3}(?:[-]\d{2})(?:[-]\d{4})?$
^ = Start of the string.
(?:…) = Grouping
\d{3} = Match 3 digits
\d{2} = Match 2 digits
\d{4} = Match 4 digits
[-] = Match a hyphen
$ = End of the string
I'm working on some validations and can't seem to wrap my head around checking for special chars, none should be used. Currently I grab the value, make an array and check for uppercase and numbers. I need a way to check for special chars as well. Another small issue I found is that it passes an uppercase when a number is entered. Just looking for some direction on how to tackle this.
$('.tooltip').on({
focusin: function(){ //make
var top = $(this).offset().top
var left = $(this).offset().left + $(this).outerWidth()
$('.tip').remove()
$('body').append("<div class='tip' style='top:"+ top +"px;left:"+left+"px;'><div class='arrow'></div></div>")
$('.tip').animate({width: 'show', opacity: 'show'})
$(tipContent).appendTo('.tip')
},
focusout: function(){ //remove
$('.tip').fadeOut(function(){$(this).remove()})
},
keyup: function(){ if (event.keyCode == 16) return //validate
var val = $(this).val()
validate(val.split(""), val);
},
})
function validate(letters, val){
for (var i = 0; i < letters.length; i++){
if( letters[i] === letters[i].toUpperCase() ) { //uppercase check
console.log(letters[i] + ": " + 'Uppercase Passed');
}else{console.log('Uppercase Failed');
}
if( letters.length >= 9 ) { //min limit
console.log(letters[i] + ": " + 'Minimum Limit Passed');
}else{console.log('Minimum Limit Failed');
}
if( parseInt(letters[i]) > 0 ) { //number check
console.log(parseInt(letters[i]) + ' passed');
}else{console.log('at least 1 char failed');
}
}
}
An option might be to use regular expressions, which make your requirements easy to formulate:
function validate(value) {
var regex = /^[A-Z0-9]*$/; // consist only of uppercase letters and digits
var digit = /\d/; // contains a digit
if (regex.test(value) && digit.test(value) && value.length >= 9)
console.log("Test passed");
else
console.log("Test failed");
}
You even could combine them to one regex:
function validate(value) {
return /^(?=.*\d)[A-Z0-9]{9,}$/.test(value);
// | | | |
// string / | consists \ string end
// beginning | of only
// / upper alphabet letters and numbers,
// somewhere ahead at least 9 of them
// comes a digit
}
OK, if you need these steps separately, we should be able to do that. To recognice uppercase letters we just could use the regex [A-Z], but then umlauts etc wouldn't be recognized. If you handled them as special chars, we can easily use this regex:
/^(?=.*\d)(?=.*[A-Z])(?=.*[^A-Za-z0-9]).{9,}$/
| | |
digit uppercase special char
If you don't want that (or the same regexes applied as single-steps), we can test for special characters with the following condition: It is not upper- or lower-caseable, and it is not a digit.
function validation(value) {
var uc = false,
lc = false,
sc = false,
di = false,
len = value.length;
for (var i=0; i<len; i++) {
var letter = value.charAt(i),
isUpper = letter.toUppercase() == letter,
isLower = letter.toLowercase() == letter;
if (isUpper && !isLower)
uc = true;
else if (isLower && !isUpper)
uc = true;
else // isLower && isUpper - no alphabetic character
if (/\d/.test(letter))
di = true;
else
sc = true;
}
return {
someUppercase: uc,
someLowercase: lc,
someSpecial: sc,
someDigit: di,
length: len,
longEnough: len >= 9
};
}
How can I format a string using Javascript to match a regex?
I am using UK postcodes which could match any of the following
N1 3LD
EC1A 3AD
GU34 8RR
I have the following regex which validates a string correctly, but I am unsure how to use the regex as a mask to format EC1A3AD to EC1A 3AD / GU348RR to GU34 8RR / N13LD to N1 3LD.
My regex is /^[A-Za-z]{1,2}[0-9A-Za-z]{1,2}[ ]?[0-9]{0,1}[A-Za-z]{2}$/
Thank you
If you use the regular expression /^([A-Z]{1,2}\d{1,2}[A-Z]?)\s*(\d[A-Z]{2})$/ you can extract the two parts of the postcode and reassemble them with an intervening space.
var list = ['N13LD', 'EC1A3AD', 'GU348RR'];
for (var i = 0; i < list.length; i++) {
var parts = list[i].match(/^([A-Z]{1,2}\d{1,2}[A-Z]?)\s*(\d[A-Z]{2})$/);
parts.shift();
alert(parts.join(' '));
}
output
N1 3LD
EC1A 3AD
GU34 8RR
Put braces around the bits separated by the optional space:
/^([A-Za-z]{1,2}[0-9A-Za-z]{1,2})[ ]?([0-9]{0,1}[A-Za-z]{2})$/
However I think the regexp is wrong... The above regexp splits "N13LD" as "N13", "LD".
I suspect the errant part is the {0,1} before the two trailing letters - there must AFAIK be exactly one digit there:
var re = /^([A-Z]{1,2}[\dA-Z]{1,2})[ ]?(\d[A-Z]{2})$/i; // case insensitive
The grouping allows the string.match(regexp) function to return a result which includes an entry for each matching group:
> "N13LD".match(re);
["N13LD", "N1", "3LD"]
> "GU348RR".match(re);
["GU348RR", "GU34", "8RR"]
> "EC1A3AD".match(re);
["EC1A3AD", "EC1A", "3AD"]
To get your result, just use trivial string concatenation to join the 2nd and 3rd element from each result together.
I've used the excellent answer from #borodin above to create a UK postcode as-you-type formatter. Note, this does not validate the postcode, just formats it according to borodin's regex as the user types.
var txtPc = $("#postcode");
var outputCount = 0;
var jigCount = 0;
var postcodePauseTime = 500;
txtPc.on("keydown", function(e) {
var keyCode = e.which;
var key = String.fromCharCode(keyCode);
var isAlphaNumeric = //key.match(/^[a-z0-9]+$/i);
(
(keyCode >= 65 && keyCode <= 90) ||
(keyCode >= 48 && keyCode <= 57) ||
([189, 190, 8, 46, 9].indexOf(keyCode) > -1) ||
(keyCode >= 35 && keyCode <= 40)
);
return !!isAlphaNumeric;
});
// handle click and add class
txtPc.on("keyup", function(e) {
PostcodeCalculateFormat(txtPc);
});
txtPc.on("blur", function() {
PostcodeCalculateFormat(txtPc);
});
function PostcodeCalculateFormat(txtPc) {
(function(index, txtPc) {
setTimeout(function() {
//prevent interferance from other keypresses by returning out of this closure
if (index != jigCount) return;
var isFocused = ($('#' + txtPc.attr('id') + ':focus')[0] == document.activeElement);
var postcodeText = txtPc.val().toUpperCase(); /// + key;
var origSpacePos = postcodeText.indexOf(" ");
postcodeText = postcodeText.replace(/[\W_]+/g, "");
var parts = postcodeText.match(/^([A-Z]{1,2}\d{1,2}[A-Z]?)\s*(\d[A-Z]{2})$/i);
//if unable to match the lot, try the first part only with less strict reg
if (!parts)
parts = postcodeText.match(/^([A-Z]{1,2}\d{1,2}[A-Z]?)\s*(.*)$/i);
if (parts) {
var caretPos = 0;
if (isFocused)
caretPos = getCaretPosition(txtPc[0]).start;
parts.shift();
var newVal = parts.join(' ');
if (newVal == txtPc.val())
return;
output(newVal);
txtPc.val(newVal);
var spacePos = newVal.indexOf(" ");
if (isFocused) {
if (caretPos >= spacePos && origSpacePos == -1)
caretPos++;
setCaretPosition(txtPc[0], caretPos, caretPos);
}
}
}, postcodePauseTime);
}(++jigCount, txtPc));
}
function output(str) {
$("#listOutput").prepend("<li>[" + (++outputCount) + "] " + str + "</li>");
}
function getCaretPosition(ctrl) {
// IE < 9 Support
if (document.selection) {
ctrl.focus();
var range = document.selection.createRange();
var rangelen = range.text.length;
range.moveStart('character', -ctrl.value.length);
var start = range.text.length - rangelen;
return {
'start': start,
'end': start + rangelen
};
}
// IE >=9 and other browsers
else if (ctrl.selectionStart || ctrl.selectionStart == '0') {
return {
'start': ctrl.selectionStart,
'end': ctrl.selectionEnd
};
} else {
return {
'start': 0,
'end': 0
};
}
}
function setCaretPosition(ctrl, start, end) {
// IE >= 9 and other browsers
if (ctrl.setSelectionRange) {
ctrl.focus();
ctrl.setSelectionRange(start, end);
}
// IE < 9
else if (ctrl.createTextRange) {
var range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character', end);
range.moveStart('character', start);
range.select();
}
}
body {
background: silver;
padding: 20px;
font-family: Helvetica;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div>Sample postcodes to type: 'BT92PE', 'EC1A3AD', 'GU348RR', 'N13LD'</div>
<div>
Postcode: <input id="postcode" style="text-transform: uppercase; " />
</div>
<!-- for troubleshooting -->
<ul id="listOutput"></ul>
The caret get & set functions were taken straight from a stack overflow answer, which I can't find right now to give the user credit. I will look & update with a link if I can.
This does everything I want it to, but it's not a very elegant solution. I'm happy for somebody out there to revamp, enhance or improve on this. I'd like to see the result.
Improvement for future: if the caret is after the space, the backspace key should remove the space AND the alphanumeric character before it in one key press. (same idea for the delete button if the caret is in before the space.)
What is the best way to perform an alphanumeric check on an INPUT field in JSP? I have attached my current code
function validateCode() {
var TCode = document.getElementById("TCode").value;
for (var i = 0; i < TCode.length; i++) {
var char1 = TCode.charAt(i);
var cc = char1.charCodeAt(0);
if ((cc > 47 && cc < 58) || (cc > 64 && cc < 91) || (cc > 96 && cc < 123)) {
} else {
alert("Input is not alphanumeric");
return false;
}
}
return true;
}
The asker's original inclination to use str.charCodeAt(i) appears to be faster than the regular expression alternative. In my test on jsPerf the RegExp option performs 66% slower in Chrome 36 (and slightly slower in Firefox 31).
Here's a cleaned-up version of the original validation code that receives a string and returns true or false:
function isAlphaNumeric(str) {
var code, i, len;
for (i = 0, len = str.length; i < len; i++) {
code = str.charCodeAt(i);
if (!(code > 47 && code < 58) && // numeric (0-9)
!(code > 64 && code < 91) && // upper alpha (A-Z)
!(code > 96 && code < 123)) { // lower alpha (a-z)
return false;
}
}
return true;
};
Of course, there may be other considerations, such as readability. A one-line regular expression is definitely prettier to look at. But if you're strictly concerned with speed, you may want to consider this alternative.
You can use this regex /^[a-z0-9]+$/i
Check it with a regex.
Javascript regexen don't have POSIX character classes, so you have to write character ranges manually:
if (!input_string.match(/^[0-9a-z]+$/))
show_error_or_something()
Here ^ means beginning of string and $ means end of string, and [0-9a-z]+ means one or more of character from 0 to 9 OR from a to z.
More information on Javascript regexen here:
https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions
You don't need to do it one at a time. Just do a test for any that are not alpha-numeric. If one is found, the validation fails.
function validateCode(){
var TCode = document.getElementById('TCode').value;
if( /[^a-zA-Z0-9]/.test( TCode ) ) {
alert('Input is not alphanumeric');
return false;
}
return true;
}
If there's at least one match of a non alpha numeric, it will return false.
To match all Unicode letters and numbers you can use a Unicode regex:
const alphanumeric = /^[\p{L}\p{N}]*$/u;
const valid = "Jòhn꠵Çoe日本語3rd"; // <- these are all letters and numbers
const invalid = "JohnDoe3rd!";
console.log(valid.match(alphanumeric));
console.log(invalid.match(alphanumeric));
In the above regex the u flag enables Unicode mode. \p{L} is short for \p{Letter} and \p{N} is short for \p{Number}. The square brackets [] surrounding them is a normal character class, meaning that a character must be either a letter or a number (in this context). The * is "zero or more", you can change this into + (one or more) if you don't want to allow empty strings .^/$ matches the start/end of the string.
The above will suffice most cases, but might match more than you want. You might not want to match Latin, Arabic, Cyrillic, etc. You might only want to match Latin letters and decimal numbers.
const alphanumeric = /^[\p{sc=Latn}\p{Nd}]*$/u;
const valid = "JòhnÇoe3rd";
const invalid = "Jòhn꠵Çoe日本語3rd";
console.log(valid.match(alphanumeric));
console.log(invalid.match(alphanumeric));
\p{sc=Latn} is short for \p{Script=Latin}. \p{Nd} is short for \p{Decimal_Number} and matches decimals. The difference with \d is that \p{Nd} does not only match 5, but also 𝟓, 5 and possibly more.
Checkout the regex Unicode documentation for details, available \p options are linked on the documentation page.
Note that the u flag is not supported by Internet Explorer.
I would create a String prototype method:
String.prototype.isAlphaNumeric = function() {
var regExp = /^[A-Za-z0-9]+$/;
return (this.match(regExp));
};
Then, the usage would be:
var TCode = document.getElementById('TCode').value;
return TCode.isAlphaNumeric()
Here are some notes: The real alphanumeric string is like "0a0a0a0b0c0d" and not like "000000" or "qwertyuio".
All the answers I read here, returned true in both cases. This is not right.
If I want to check if my "00000" string is alphanumeric, my intuition is unquestionably FALSE.
Why? Simple. I cannot find any letter char. So, is a simple numeric string [0-9].
On the other hand, if I wanted to check my "abcdefg" string, my intuition
is still FALSE. I don't see numbers, so it's not alphanumeric. Just alpha [a-zA-Z].
The Michael Martin-Smucker's answer has been illuminating.
However he was aimed at achieving better performance instead of regex. This is true, using a low level way there's a better perfomance. But results it's the same.
The strings "0123456789" (only numeric), "qwertyuiop" (only alpha) and "0a1b2c3d4f4g" (alphanumeric) returns TRUE as alphanumeric. Same regex /^[a-z0-9]+$/i way.
The reason why the regex does not work is as simple as obvious. The syntax [] indicates or, not and.
So, if is it only numeric or if is it only letters, regex returns true.
But, the Michael Martin-Smucker's answer was nevertheless illuminating. For me.
It allowed me to think at "low level", to create a real function that unambiguously
processes an alphanumeric string. I called it like PHP relative function ctype_alnum (edit 2020-02-18: Where, however, this checks OR and not AND).
Here's the code:
function ctype_alnum(str) {
var code, i, len;
var isNumeric = false, isAlpha = false; // I assume that it is all non-alphanumeric
for (i = 0, len = str.length; i < len; i++) {
code = str.charCodeAt(i);
switch (true) {
case code > 47 && code < 58: // check if 0-9
isNumeric = true;
break;
case (code > 64 && code < 91) || (code > 96 && code < 123): // check if A-Z or a-z
isAlpha = true;
break;
default:
// not 0-9, not A-Z or a-z
return false; // stop function with false result, no more checks
}
}
return isNumeric && isAlpha; // return the loop results, if both are true, the string is certainly alphanumeric
}
And here is a demo:
function ctype_alnum(str) {
var code, i, len;
var isNumeric = false, isAlpha = false; //I assume that it is all non-alphanumeric
loop1:
for (i = 0, len = str.length; i < len; i++) {
code = str.charCodeAt(i);
switch (true){
case code > 47 && code < 58: // check if 0-9
isNumeric = true;
break;
case (code > 64 && code < 91) || (code > 96 && code < 123): //check if A-Z or a-z
isAlpha = true;
break;
default: // not 0-9, not A-Z or a-z
return false; //stop function with false result, no more checks
}
}
return isNumeric && isAlpha; //return the loop results, if both are true, the string is certainly alphanumeric
};
$("#input").on("keyup", function(){
if ($(this).val().length === 0) {$("#results").html(""); return false};
var isAlphaNumeric = ctype_alnum ($(this).val());
$("#results").html(
(isAlphaNumeric) ? 'Yes' : 'No'
)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="input">
<div> is Alphanumeric?
<span id="results"></span>
</div>
This is an implementation of Michael Martin-Smucker's method in JavaScript.
// On keypress event call the following method
function AlphaNumCheck(e) {
var charCode = (e.which) ? e.which : e.keyCode;
if (charCode == 8) return true;
var keynum;
var keychar;
var charcheck = /[a-zA-Z0-9]/;
if (window.event) // IE
{
keynum = e.keyCode;
}
else {
if (e.which) // Netscape/Firefox/Opera
{
keynum = e.which;
}
else return true;
}
keychar = String.fromCharCode(keynum);
return charcheck.test(keychar);
}
Further, this article also helps to understand JavaScript alphanumeric validation.
In a tight loop, it's probably better to avoid regex and hardcode your characters:
const CHARS = new Set("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
function isAlphanumeric(char) {
return CHARS.has(char);
}
To check whether input_string is alphanumeric, simply use:
input_string.match(/[^\w]|_/) == null
If you want a simplest one-liner solution, then go for the accepted answer that uses regex.
However, if you want a faster solution then here's a function you can have.
console.log(isAlphaNumeric('a')); // true
console.log(isAlphaNumericString('HelloWorld96')); // true
console.log(isAlphaNumericString('Hello World!')); // false
/**
* Function to check if a character is alpha-numeric.
*
* #param {string} c
* #return {boolean}
*/
function isAlphaNumeric(c) {
const CHAR_CODE_A = 65;
const CHAR_CODE_Z = 90;
const CHAR_CODE_AS = 97;
const CHAR_CODE_ZS = 122;
const CHAR_CODE_0 = 48;
const CHAR_CODE_9 = 57;
let code = c.charCodeAt(0);
if (
(code >= CHAR_CODE_A && code <= CHAR_CODE_Z) ||
(code >= CHAR_CODE_AS && code <= CHAR_CODE_ZS) ||
(code >= CHAR_CODE_0 && code <= CHAR_CODE_9)
) {
return true;
}
return false;
}
/**
* Function to check if a string is fully alpha-numeric.
*
* #param {string} s
* #returns {boolean}
*/
function isAlphaNumericString(s) {
for (let i = 0; i < s.length; i++) {
if (!isAlphaNumeric(s[i])) {
return false;
}
}
return true;
}
const isAlphaNumeric = (str) => {
let n1 = false,
n2 = false;
const myBigBrainString =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
const myHackyNumbers = "0123456789";
for (let i = 0; i < str.length; i++) {
if (myBigBrainString.indexOf(str.charAt(i)) >= 0) {
n1 = true;
}
if (myHackyNumbers.indexOf(str.charAt(i)) >= 0) {
n2 = true;
}
if (n1 && n2) {
return true;
}
}
return n1 && n2;
};
Works till eternity..
Removed NOT operation in alpha-numeric validation. Moved variables to block level scope. Some comments here and there. Derived from the best Micheal
function isAlphaNumeric ( str ) {
/* Iterating character by character to get ASCII code for each character */
for ( let i = 0, len = str.length, code = 0; i < len; ++i ) {
/* Collecting charCode from i index value in a string */
code = str.charCodeAt( i );
/* Validating charCode falls into anyone category */
if (
( code > 47 && code < 58) // numeric (0-9)
|| ( code > 64 && code < 91) // upper alpha (A-Z)
|| ( code > 96 && code < 123 ) // lower alpha (a-z)
) {
continue;
}
/* If nothing satisfies then returning false */
return false
}
/* After validating all the characters and we returning success message*/
return true;
};
console.log(isAlphaNumeric("oye"));
console.log(isAlphaNumeric("oye123"));
console.log(isAlphaNumeric("oye%123"));
(/[^0-9a-zA-Z]/.test( "abcdeFGh123456" ));
Convert string to alphanumeric (Usefull in case of files names)
function stringToAlphanumeric(str = ``) {
return str
.split('')
.map((e) => (/^[a-z0-9]+$/i.test(e) ? e : '_'))
.join('')
}
const fileName = stringToAlphanumeric(`correct-('"é'è-///*$##~~*\\\"filename`)
console.log(fileName)
// expected output "correct_filename"