Table of Contents
Removing special characters from user input values before sending to database is very common client side validation that every web developer must apply to secure application.
Learn More –
- Laravel 9 How To Block Whitelist IP Address Tutorial
- Laravel 9 Create Multi Language Website Using Google Translator
- How To Generate Random Unique Token in PHP Tutorial
- Laravel 9 How to Call a Controller Function in Another Controller
Let’s get started.
Remove Special Characters From String
Create index.html file in your localhost path. Open file and add this code into it.
//... <script> var str = 'Hello !@#$%^Online &&Web *& Tutor?.'; var noSpecialCharacters = str.replace(/[^a-zA-Z0-9 ]/g, ''); console.log(noSpecialCharacters); </script> //...
To remove special characters from string values, we used regular expression.
var noSpecialCharacters = str.replace(/[^a-zA-Z0-9 ]/g, '');
This regular expression will remove all special characters which are not in the given set. This given set contains characters from a-z, A-Z, 0-9 and space.
Also, we have an alternative way to do this special characters replacement. We use a known regular expression i.e [^\w ]
The above regular expression auto generates the set of a-z, A-Z, 0-9, _ and space.
Open index.html and add this code.
//... <script> var str = 'Hello !@#$%^Online &&Web *& Tutor?.'; var noSpecialCharacters = str.replace(/[^\w ]/g, ''); console.log(noSpecialCharacters); </script> //...
var noSpecialCharacters = str.replace(/[^\w ]/g, '');
Online Web Tutor invites you to try Skillshare free for 1 month! Learn CakePHP 4, Laravel APIs Development, CodeIgniter 4, Node Js, etc into a depth level. Master the Coding Skills to Become an Expert in Web Development. So, Search your favourite course and enroll now. Click here to join.