Restricting characters in text box - javascript

I need to modify this function to work properly. It is supposed to restrict everything but the alphabet, spaces, and apostrophes. Currently it is still restricting apostrophes. I'm assuming the pattern ' \ _ ' is referring to ALL special characters. How would I insert an exception in to this function?
function NameNotNA (s) {
var pattern;
if (s.toUpperCase().indexOf('N/A') != -1){
//console.warn('failed in n/a');
return false;
}
// Eliminate possibility of digits
pattern = /\d/;
if (s.match(pattern) != null) {
//console.warn('failed in \d');
return false;
}
pattern = /\_/;
if (s.match(pattern) != null) {
//console.warn('failed in \_');
return false;
}
s = s.replace(/ /g, '');
if (s.match(/\W/) != null) {
return false;
}
return true;
}

function nameNotNA (s) {
return s.replace(/[^\w\s']/g, '');
}
For regex, I like using this tool to understand exactly what's happening. Also, it's good to keep your function names lowerCamelCase unless it's a Class.

Related

Delete special characters from an ng-repeat list (parsed from CSV) [duplicate]

I want to remove all special characters except space from a string using JavaScript.
For example,
abc's test#s
should output as
abcs tests.
You should use the string replace function, with a single regex.
Assuming by special characters, you mean anything that's not letter, here is a solution:
const str = "abc's test#s";
console.log(str.replace(/[^a-zA-Z ]/g, ""));
You can do it specifying the characters you want to remove:
string = string.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g, '');
Alternatively, to change all characters except numbers and letters, try:
string = string.replace(/[^a-zA-Z0-9]/g, '');
The first solution does not work for any UTF-8 alphabet. (It will cut text such as Привіт). I have managed to create a function which does not use RegExp and use good UTF-8 support in the JavaScript engine. The idea is simple if a symbol is equal in uppercase and lowercase it is a special character. The only exception is made for whitespace.
function removeSpecials(str) {
var lower = str.toLowerCase();
var upper = str.toUpperCase();
var res = "";
for(var i=0; i<lower.length; ++i) {
if(lower[i] != upper[i] || lower[i].trim() === '')
res += str[i];
}
return res;
}
Update: Please note, that this solution works only for languages where there are small and capital letters. In languages like Chinese, this won't work.
Update 2: I came to the original solution when I was working on a fuzzy search. If you also trying to remove special characters to implement search functionality, there is a better approach. Use any transliteration library which will produce you string only from Latin characters and then the simple Regexp will do all magic of removing special characters. (This will work for Chinese also and you also will receive side benefits by making Tromsø == Tromso).
search all not (word characters || space):
str.replace(/[^\w ]/, '')
I don't know JavaScript, but isn't it possible using regex?
Something like [^\w\d\s] will match anything but digits, characters and whitespaces. It would be just a question to find the syntax in JavaScript.
I tried Seagul's very creative solution, but found it treated numbers also as special characters, which did not suit my needs. So here is my (failsafe) tweak of Seagul's solution...
//return true if char is a number
function isNumber (text) {
if(text) {
var reg = new RegExp('[0-9]+$');
return reg.test(text);
}
return false;
}
function removeSpecial (text) {
if(text) {
var lower = text.toLowerCase();
var upper = text.toUpperCase();
var result = "";
for(var i=0; i<lower.length; ++i) {
if(isNumber(text[i]) || (lower[i] != upper[i]) || (lower[i].trim() === '')) {
result += text[i];
}
}
return result;
}
return '';
}
const str = "abc's#thy#^g&test#s";
console.log(str.replace(/[^a-zA-Z ]/g, ""));
Try to use this one
var result= stringToReplace.replace(/[^\w\s]/g, '')
[^] is for negation, \w for [a-zA-Z0-9_] word characters and \s for space,
/[]/g for global
With regular expression
let string = "!#This tool removes $special *characters* /other/ than! digits, characters and spaces!!!$";
var NewString= string.replace(/[^\w\s]/gi, '');
console.log(NewString);
Result //This tool removes special characters other than digits characters and spaces
Live Example : https://helpseotools.com/text-tools/remove-special-characters
dot (.) may not be considered special. I have added an OR condition to Mozfet's & Seagull's answer:
function isNumber (text) {
reg = new RegExp('[0-9]+$');
if(text) {
return reg.test(text);
}
return false;
}
function removeSpecial (text) {
if(text) {
var lower = text.toLowerCase();
var upper = text.toUpperCase();
var result = "";
for(var i=0; i<lower.length; ++i) {
if(isNumber(text[i]) || (lower[i] != upper[i]) || (lower[i].trim() === '') || (lower[i].trim() === '.')) {
result += text[i];
}
}
return result;
}
return '';
}
Try this:
const strippedString = htmlString.replace(/(<([^>]+)>)/gi, "");
console.log(strippedString);
const input = `#if_1 $(PR_CONTRACT_END_DATE) == '23-09-2019' #
Test27919<alerts#imimobile.com> #elseif_1 $(PR_CONTRACT_START_DATE) == '20-09-2019' #
Sender539<rama.sns#gmail.com> #elseif_1 $(PR_ACCOUNT_ID) == '1234' #
AdestraSID<hello#imimobile.co> #else_1#Test27919<alerts#imimobile.com>#endif_1#`;
const replaceString = input.split('$(').join('->').split(')').join('<-');
console.log(replaceString.match(/(?<=->).*?(?=<-)/g));
Whose special characters you want to remove from a string, prepare a list of them and then user javascript replace function to remove all special characters.
var str = 'abc'de#;:sfjkewr47239847duifyh';
alert(str.replace("'","").replace("#","").replace(";","").replace(":",""));
or you can run loop for a whole string and compare single single character with the ASCII code and regenerate a new string.

Replace matches with regex

I am trying to replace matches of text between dollar signs.
So the text $match$ inside Some text and $some text that matches$. should be replaced.
I have tried
text.replace(/\$.*?\$/g, function (match) {
return '_' + match + '_';
}
This works. The problem is that I want to do evaluate the match inside this function, but sometimes the evaluation didn't work, and in these cases I just want to return the original match. So it is something like
text.replace(/\$.*?\$/g, function (match) {
try {
return evaluate(match);
} catch (e) {
return match;
}
}
But with my current regex, the match contains the dollar signs from the original text. I want it to omit the dollar signs, but if the evaluation fails, then I want the original dollar signs back.
What I could do is
text.replace(/\$.*?\$/g, function (match) {
try {
return evaluate(match.replace(/\$/g, ''));
} catch (e) {
return match;
}
}
but isn't it possible in a more elegant way?
Something like this might do:
const evaluate = function(str) {
if (str && str.startsWith("t")) {return str.toUpperCase();}
throw "Gotta hava a 'T'";
};
"ab$test$cd $something$ that is $tricky$.".replace(/\$([^$]*)\$/g;, function(str, match) {
try {
return evaluate(match);
} catch(e) {
return str;
}
}); //=> "abTESTcd $something$ that is TRICKY."
But I agree with the comment that you might be better returning a different signal (undefined? null?) from evaluate rather than throwing for this case. And then the function body could simply be something like:
return evaluate(match) || str;
The point is the capturing group in the regex: /\$([^$]*)\$/g;, which becomes a parameter to the replacement function.

javascript code to check special characters

I have JavaScript code to check if special characters are in a string. The code works fine in Firefox, but not in Chrome. In Chrome, even if the string does not contain special characters, it says it contains special characters.
var iChars = "~`!#$%^&*+=-[]\\\';,/{}|\":<>?";
for (var i = 0; i < chkfile.value.length; i++)
{
if (iChars.indexOf(chkfile.value.charAt(i)) != -1)
{
alert ("File name has special characters ~`!#$%^&*+=-[]\\\';,/{}|\":<>? \nThese are not allowed\n");
return false;
}
}
Suppose I want to upload a file desktop.zip from any Linux/Windows machine.
The value of chkfile.value is desktop.zip in Firefox, but in Chrome the value of chkfile.value is c://fakepath/desktop.zip. How do I get rid of c://fakepath/ from chkfile.value?
You can test a string using this regular expression:
function isValid(str){
return !/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
}
Try This one.
function containsSpecialCharacters(str){
var regex = /[ !##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/g;
return regex.test(str);
}
Directly from the w3schools website:
var str = "The best things in life are free";
var patt = new RegExp("e");
var res = patt.test(str);
To combine their example with a regular expression, you could do the following:
function checkUserName() {
var username = document.getElementsByName("username").value;
var pattern = new RegExp(/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/); //unacceptable chars
if (pattern.test(username)) {
alert("Please only use standard alphanumerics");
return false;
}
return true; //good user input
}
Did you write return true somewhere? You should have written it, otherwise function returns nothing and program may think that it's false, too.
function isValid(str) {
var iChars = "~`!#$%^&*+=-[]\\\';,/{}|\":<>?";
for (var i = 0; i < str.length; i++) {
if (iChars.indexOf(str.charAt(i)) != -1) {
alert ("File name has special characters ~`!#$%^&*+=-[]\\\';,/{}|\":<>? \nThese are not allowed\n");
return false;
}
}
return true;
}
I tried this in my chrome console and it worked well.
You could also do it this way.
specialRegex = /[^A-Z a-z0-9]/
specialRegex.test('test!') // evaluates to true
Because if its not a capital letter, lowercase letter, number, or space, it could only be a special character
If you don't want to include any special character, then try this much simple way for checking special characters using RegExp \W Metacharacter.
var iChars = "~`!#$%^&*+=-[]\\\';,/{}|\":<>?";
if(!(iChars.match(/\W/g)) == "") {
alert ("File name has special characters ~`!#$%^&*+=-[]\\\';,/{}|\":<>? \nThese are not allowed\n");
return false;
}

Regular expression escaping tab key

Hi I want to allow alphanumeric + _ in a text box. but when I press tab it warns me about the special characters are not allowed. Here is the Javascript code. Is there a way to escape tab and carriage return using regular expressions ?
function splChars(str)
{
if (str != "")
{
if (/^[\w _\t\r]+$/.test(str))
return true;
else
return false;
}
}
I think this is what you want:
.replace(/([^a-z0-9_])/gi, '\\$1');
eg:
'abd12^_$'.replace(/([^a-z0-9_])/gi, '\\$1') // "abd12\^_\$"

JavaScript - checking for any lowercase letters in a string

Consider a JavaScript method that needs to check whether a given string is in all uppercase letters. The input strings are people's names.
The current algorithm is to check for any lowercase letters.
var check1 = "Jack Spratt";
var check2 = "BARBARA FOO-BAR";
var check3 = "JASON D'WIDGET";
var isUpper1 = HasLowercaseCharacters(check1);
var isUpper2 = HasLowercaseCharacters(check2);
var isUpper3 = HasLowercaseCharacters(check3);
function HasLowercaseCharacters(string input)
{
//pattern for finding whether any lowercase alpha characters exist
var allLowercase;
return allLowercase.test(input);
}
Is a regex the best way to go here?
What pattern would you use to determine whether a string has any lower case alpha characters?
function hasLowerCase(str) {
return str.toUpperCase() != str;
}
console.log("HeLLO: ", hasLowerCase("HeLLO"));
console.log("HELLO: ", hasLowerCase("HELLO"));
also:
function hasLowerCase(str) {
return (/[a-z]/.test(str));
}
function hasLowerCase(str) {
return str.toUpperCase() != str;
}
or
function hasLowerCase(str) {
for(x=0;x<str.length;x++)
if(str.charAt(x) >= 'a' && str.charAt(x) <= 'z')
return true;
return false;
}
Another solution only match regex to a-z
function nameHere(str) {
return str.match(/[a-z]/);
}
or
function nameHere(str) {
return /[a-z]/g.test(str);
}

Categories

Resources