Remove all special characters with RegExp
var desired = stringToReplace.replace(/[^\w\s]/gi, '')
As was mentioned in the comments it's easier to do this as a whitelist - replace the characters which aren't in your safelist.
The caret (^
) character is the negation of the set [...]
, gi
say global and case-insensitive (the latter is a bit redundant but I wanted to mention it) and the safelist in this example is digits, word characters, underscores (\w
) and whitespace (\s
).
How to remove special characters from a string using Javascript
Try with this function:
function removeSpecialChars(str) {
return str.replace(/(?!\w|\s)./g, '')
.replace(/\s+/g, ' ')
.replace(/^(\s*)([\W\w]*)(\b\s*$)/g, '$2');
}
- 1st regex
/(?!\w|\s)./g
remove any character that is not a word or whitespace.\w
is equivalent to[A-Za-z0-9_]
- 2nd regex
/\s+/g
find any appearance of 1 or more whitespaces and replace it with one single white space - 3rd regex
/^(\s*)([\W\w]*)(\b\s*$)/g
trim the string to remove any whitespace at the beginning or the end.
Regex to remove specific special characters
Use the string.replace()
method and the unicode escape codes for your special characters. You have to use the \
character to escape in JavaScript regex
var str = 'Here is a \' string \" with \" \' some @ special ® characters ™ & &'
str.replace(/['"\u0040\u0026\u2122\u00ae]/g, '')
/pattern/
denotes a regex pattern in JavaScript
[charset]
says which set of characters to match
/g
specifies global matches so it will replace all occurrences
Remove all special characters except space from a string using JavaScript
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, ""));
Regex remove all special characters except numbers?
Use the global flag:
var name = name.replace(/[^a-zA-Z ]/g, "");
^
If you don't want to remove numbers, add it to the class:
var name = name.replace(/[^a-zA-Z0-9 ]/g, "");
Javascript - Regex expression to remove special characters from title
You can use
let title = "Pet Supplies (Cat and Dog)"
title = title.toLowerCase() // Turn to lower
.match(/[a-z0-9\s-]+/g) // Extract all alnum + hyphen and whitespace chunks
.map(x => x.trim().split(/\s+/).join("-")) // Trim the items, split with whitespace and join with a hyphen
.join("-") // Join the items with a hyphen
.replace(/-and\b/g, ''); // Remove whole word -and
console.log(title);
Remove Letters and special characters
If you want to filter out letters and special characters you can use regular expression in JS, like this:
id = id.replace(/\D/g, "")
You replace every (g
option) character in your string that is not a digit \D
with blank ""
How to remove special characters like $, @, % from string in jquery
You should explore Regex.
Try this:
var str = 'The student have 100% of attendance in @school';str= str.replace(/[^\w\s]/gi, '')document.write(str);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
regex to remove special characters, spaces and number if first character
You can use following regular expression:
/^\d+|[\W_]+/g
^\d+
: to match leading digits (Use^\d
if you want to remove only one leading digit)\W
: to match non word character (reverse of\w
:\w
matches digit/alphabet/_
)[\W_]
: to include_
because\W
does not include_
'1 step for man & 2 steps for others 123!'.replace(/^\d+|[\W_]+/g, '')
# => "stepforman2stepsforothers123"
'step for 1 man & 2 steps for others 123!'.replace(/^\d+|[\W_]+/g, '')
# => "stepfor1man2stepsforothers123"
Regex remove special characters in filename except extension
You may remove any chars other than word and dot chars with [^\w.]
and any dot not followed with 1+ non-dot chars at the end of the string:
filename = filename.replace(/(?:\.(?![^.]+$)|[^\w.])+/g, "-");
See the regex demo
Details
(?:
- start of a non-capturing group:\.(?![^.]+$)
- any dot not followed with 1+ non-dot chars at the end of the string|
- or[^\w.]
- any char other than a word char and a dot char
)+
- end of the group, repeat 1 or more times.
Another solution (if extensions are always present): split out the extension, run your simpler regex on the first chunk then join back:
var filename = "manuel fernandex – Index Prot.bla.otype 5 (pepito grillo).jpg";var ext = filename.substr(filename.lastIndexOf('.') + 1);var name = filename.substr(0, filename.lastIndexOf('.')); console.log(name.replace(/\W+/g, "-") + "." + ext);
Related Topics
How to Change the Width of Angular Material Button
Node.Js Call Function If Button Clicked
Call PHP Function With Onclick Event
How to Detect String Which Contains Only Spaces
How to Find Matching Values in Two Arrays
Javascript Blob Filename Without Link
Google Script to See If Text Contains a Value
Convert JavaScript Date Format to Yyyy-Mm-Ddthh:Mm:Ss
Safari Browser Audio.Play() Is Not Working
How to Display an Image from an Array of Images in React
How to Set a Header Field on Post a Form
Get the Contents of a Table Row With a Button Click
Angular2 Do Actions After Dom Has Finished Rendering
To Get a Popup Message After Submit
Center Content Vertically on Vuetify
Disable/Hide Download Button in Iframe on Default Pdf Viewer