Remove unwanted Characters using Javascript (JS)

Remove unwanted characters using JS

Using below JS (Javascript), you can remove the unwanted characters on your content

(a) Code to Remove Non-numerical characters

var ele = ” 123!456@&^%5string990.00 “;
var req = ele.replace(“/[^0-9]/g”,””); // or var req = ele.replace(“/\D/g”,””);
alert(req); //Result = 123456599000

(b) Code to Remove Non-alphabetic characters
var ele = ” 123!456@&^%5string990.00 “;
var req = ele.replace(“/[^a-zA-Z]/g”,””);
alert(req); //Result = string

(c) Code to Remove non-alphanumeric characters
var ele = ” 123!456@&^%5string990.00 “;
var req = ele.replace(“/[^a-zA-Z0-9]/g”,””);
alert(req); //Result = 1234565string99000

(d) Code to Remove white_space only
var ele = ” 123!456 @&^%5 string 990.00 “;
var req = ele.replace(“/\s/g”,””);
alert(req); //Result = 123!456@&^%5string 990.00 (Remove all white spaces in a varible)

Notes: syntax => element.replace(expression,replace_content);
1.Some Expressions are,
“/[0-9]/g” or “/ \d/ g” => Select digits only
“/[^0-9]/g” or “/ \D /g” => Select all non-digits
“/[a-zA-Z]/g” => Select Alphabetics only
“/[^a-zA-Z]/g” or “/ \D /g” => Select all non-alphabetics
“/[a-zA-Z0-9]/g” or “/ \D /g” => Select all Alpha-numeric characters
“/[^a-zA-Z0-9]/g” or “/ \D /g” => Select all Non-alphanumeric characters
2.Replace_Content => you can add any variable type as a replace content include white-space(” “) and empty field(“”).

Leave a Reply