Hello everyone, I am going share the code sample for how to Replace Special Charactersfrom String like you can see the
below image.
In the above output image, you can see, when I clicked on "Remove Special Characters" button to display an alert text-box input text are not showing the special characters
in the result string but I putting the some special charters in the in the text-box, you can see, edit and click on below given plunker link.
For
live demo go to http://embed.plnkr.co/06dJ3A/preview
The
JavaScript code
with regular expression for Replacing Special Characters from String as give below
function removeSpecialCharacters() {
var regExpr = /[^a-zA-Z0-9-. ]/g;
var userText =
document.getElementById('user').value;
alert(userText.replace(regExpr, ""));
}
The
Full Live demo code
as given below
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>JavaScript Regular Expression
to Replace Special Characters from String</title>
<link rel="stylesheet" href="style.css" />
<script data-require="jquery" data-semver="2.1.4" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
function removeSpecialCharacters() {
var
regExpr = /[^a-zA-Z0-9-.
]/g;
var
userText = document.getElementById('user').value;
alert(userText.replace(regExpr, ""));
}
</script>
</head>
<body>
<div>
<h1>JavaScript Regular Expression
to Replace Escape Special Characters from String</h1>
</div>
<div>
<h2>Enter Your Input Text</h2>
</div>
<div>
<input type="text" id="user" value="Hello Anil' Welcome
you to#$% code-@!sample.$*^com" class="text" />
<input type="button" id="btnRemove" value="Remove Special
Characters"
onclick="removeSpecialCharacters()" class="success" />
</div>
</body>
</html>
The CSS code for Textbox and
button as given below
<style>
h1 {
color: Green;
}
.success {
background-color: #57A957;
color: white;
background-repeat: no-repeat;
display: inline-block;
height: 40px;
vertical-align: middle;
}
.text {
height: 36px;
position: relative;
border: 1px solid #cdcdcd;
font-size: 14px;
width: 300px;
}
</style>
The output : go to link http://embed.plnkr.co/06dJ3A/preview
Thank you!