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;
}
Related
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.
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.
I'm going through an exercise and one of the functions is to write code that takes an input containing only strings and returns the first
non-repeating character.
I've done that already, but i would like to make it smarter by handling any errors that could be a number or symbol. I tried all I could but it seems not to work. It should be purely letters and spaces taken.
Here is what I have so far.
function TheOutput(word){
var a =word.length;
for(var i=0; i < a; i++){
var char=word.charAt(i);
if(word.indexOf(char)===word.lastIndexOf(char)){
result = (char + " is not a number <br/>");
break;
}
return result;
}
}
You can use regular expressions if you want to test if string is containing only letters and spaces.
var onlyLettersAndSpace = 'Valid string';
var stringWithNumbers = 'Invalid string 123';
var RegExpression = new RegExp(/^[a-zA-Z\s]*$/);
console.log(RegExpression.test(onlyLettersAndSpace));
// true
console.log(RegExpression.test(stringWithNumbers));
// false
In your case, you could do something like:
function testWord(word) {
var RegExpression = new RegExp(/^[a-zA-Z\s]*$/);
return RegExpression.test(word);
}
You can do a lot more with regular expressions, see RegExp MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp
I want that the first two characters of my string should not be special characters
function detectInvalidChars(limitField)
{
var len=limitField.value.length;
var char1=limitField.value.substring(0,1);
var char2=limitField.value.substring(1,2);
if(char1=='&'||char1=='<' char1=='!' || char2=='&'||char2=='<'..........so on)
{
alert("Invalid character");
limitField.value = limitField.value.substring(0,len-1);
}
}
instead of matching the char1 and char2 with each special character. What can I do?
You can use a regular expression:
var re = /^([&<!]|.[&<!])/;
if (re.test(limitField.value)) {
alert...
}
look into the string method .charCodeAt(n)
you should be able to then compare the ascii values in ranges.
so for example if you want to exclude control charactercs you could write something like
if (mystring.charCodeAt(0)<32 || mystring.charCodeAt(1)<32) {
alert("Invalid character");
}
or use a regex.
You may find this question helpful:
isalpha replacement for JavaScript?
You can use regex for that on a substring of the original.
substring gets the part of the string from "from" to "to".
/^[0-9a-z]+$/ is regex that allows only 0 ... 9 and a ... z
function is_part_alnum(value, from, to)
substring = value.substring(from, to);
if(!substring.match(/^[0-9a-z]+$/) {
alert("Invalid character(s)");
}
}
If you don't want to use regex and want to define your own set of special characters, you could use a function like this:
function detectInvalidChars(s, count) {
var specialChars = "!##$%^&*()+=-[]\\\';,./{}|\":<>?~_";
var firstChars = s.substr(0, count).split('');
for(var i=0; i<firstChars.length; i++) {
if(specialChars.indexOf(firstChars[i]) !== -1) {
// invalid char detected
}
}
}
Where s is your string and count is the number of the first characters that should be investigated.
I know I can validate against string with words ( 0-9 A-Z a-z and underscore ) by applying W in regex like this:
function isValid(str) { return /^\w+$/.test(str); }
But how do I check whether the string contains ASCII characters only? ( I think I'm close, but what did I miss? )
Reference: https://stackoverflow.com/a/8253200/188331
UPDATE : Standard character set is enough for my case.
All you need to do it test that the characters are in the right character range.
function isASCII(str) {
return /^[\x00-\x7F]*$/.test(str);
}
Or if you want to possibly use the extended ASCII character set:
function isASCII(str, extended) {
return (extended ? /^[\x00-\xFF]*$/ : /^[\x00-\x7F]*$/).test(str);
}
You don't need a RegEx to do it, just check if all characters in that string have a char code between 0 and 127:
function isValid(str){
if(typeof(str)!=='string'){
return false;
}
for(var i=0;i<str.length;i++){
if(str.charCodeAt(i)>127){
return false;
}
}
return true;
}
For ES2018, Regexp support Unicode property escapes, you can use /[\p{ASCII}]+/u to match the ASCII characters. It's much clear now.
Supported browsers:
Chrome 64+
Safari/JavaScriptCore beginning in Safari Technology Preview 42
var check = function(checkString) {
var invalidCharsFound = false;
for (var i = 0; i < checkString.length; i++) {
var charValue = checkString.charCodeAt(i);
/**
* do not accept characters over 127
**/
if (charValue > 127) {
invalidCharsFound = true;
break;
}
}
return invalidCharsFound;
};