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
.
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
).
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 '';
}
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 '';
}
const input = `#if_1 $(PR_CONTRACT_END_DATE) == '23-09-2019' #
Test27919<[email protected]> #elseif_1 $(PR_CONTRACT_START_DATE) == '20-09-2019' #
Sender539<[email protected]> #elseif_1 $(PR_ACCOUNT_ID) == '1234' #
AdestraSID<[email protected]> #else_1#Test27919<[email protected]>#endif_1#`;
const replaceString = input.split('$(').join('->').split(')').join('<-');
console.log(replaceString.match(/(?<=->).*?(?=<-)/g));
Try this to achieve the same results I have a sample here, you can edit it or make it more efficient:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Validation example</title>
</head>
<body>
<div>
<!-- optional form element for HTML5 Validation on submit
- the Vanilla js code below can work well without a form element
=====================================================
So you can decide to use the HTML5 validation on top of JS validation when you use a form with a submit button
But if you use the input element only then you have to rely on the js validation only
-->
<form id="search-form">
<input type="text" pattern="[A-Za-z\s0-9]{3,}" title="Only letters, numbers and spaces are allowed" placeholder="Search" name="search" id="search-input">
<!-- optional submit button if using a form -->
<button type="submit">Submit</button>
</form>
</div>
<script>
window.onload = function () {
var inputElementRef = document.getElementById("search-input"); //use id selector for precise selection in a large html document
var inputSearchValue = "";
inputElementRef.addEventListener("keydown", function (e) {
inputSearchValue = e.target.value;
// replace invalid characters if you are not using HTML5 validation this will ensure the value
// is always the expected string format
inputSearchValue = inputSearchValue.replace(/[^a-zA-Z\s]/g,"");
});
// whenever you change the value you can retrieve it from var inputSearchValue
// For example
var handleFormSubmit = function (e) {
e.preventDefault();
console.log('inputSearchValue', inputSearchValue)
}
var optionalSearchFormRef = document.getElementById("search-form");
optionalSearchFormRef.addEventListener("submit", handleFormSubmit);
}
</script>
</body>
</html>
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.