Aspdotnet-Suresh

aspdotnet-suresh offers C#.net articles and tutorials,csharp dot net,asp.net articles and tutorials,VB.NET Articles,Gridview articles,code examples of asp.net 2.0 /3.5,AJAX,SQL Server Articles,examples of .net technologies

JavaScript Regular Expression to Replace (Escape) Special Characters from String

Jul 1, 2015
Introduction

Here I will explain how to use
JavaScript regular expression to remove special characters or regular expression to escape special characters in JavaScript or regex to replace special characters in string using JavaScript. By using JavaScript replace function we can replace or remove special characters in string.


To replace special characters with regular expression we need to write the code like as shown below


<script type="text/javascript">
function escapecharacters() {
var str = document.getElementById('txtDetails').value;
// It will replace all characters except alphabets, characters. and space
alert(str.replace(/[^a-zA-Z0-9-. ]/g, ""));
}
</script>

In above code “^” symbol in regular expression will leave mentioned characters and replace or remove other characters.

If you want to check it in complete example you need to write the code like as shown below


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Javascript regular expression to replace (Escape) special characters</title>
<script type="text/javascript">
function escapecharacters() {
var str = document.getElementById('txtDetails').value;
// It will replace all characters except alphabets, characters. and space
alert(str.replace(/[^a-zA-Z0-9-. ]/g, ""));
}
</script>
</head>
<body>
<form id="form1">
<div>
Enter Message:<input type="text" id="txtDetails" value="hello' welcome to#$% aspdotnet-@!suresh.com" />
<input type="button" id="btnRemove" value="Remove Characters" onclick="escapecharacters()" />
</div>
</form>
</body>
</html>

Live Demo

For live demo click on below button by entering text in textbox with special characters


Enter Message:
  

If you enjoyed this post, please support the blog below. It's FREE!

Get the latest Asp.net, C#.net, VB.NET, jQuery, Plugins & Code Snippets for FREE by subscribing to our Facebook, Twitter, RSS feed, or by email.

subscribe by rss Subscribe by RSS subscribe by email Subscribe by Email

0 comments :

Give your Valuable Comments

Other Related Posts

© 2015 Aspdotnet-Suresh.com. All Rights Reserved.
The content is copyrighted to Suresh Dasari and may not be reproduced on other websites without permission from the owner.