Replace Word in a Text using jQuery

This post is written by guest blogger Aamir Hasan

Yesterday someone asked me how to replace a word in a text using jQuery. To demonstrate that, let us read text from a Div control, replace it with our text and then assign the replaced text to that Div, as shown in below example:

Note: This code will replace only the first occurrence of the word.

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Replace Word in a Text using jQuery</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
   1:  
   2:     
</script>
   1:  
   2:      <script type="text/javascript" language="javascript">
   3:          $(function () {
   4:              $("#btnReplace").click(function () {
   5:                  $("#div1").html($("#div1").html().replace("aamir", "Aamir Hasan"));
   6:              });
   7:          }); 
   8:     
</script>
</head>
<body>
<div id="div1">My name is aamir</div><br />
<input id="btnReplace" type="button" value="Replace" />
</body>
</html>


image

See a Live Demo

Aamir Hasan, is a Sr. Software Engineer and Technical Lead in a US based firm, having five years of experiences working in Software Design, Web Development, Consultancy and Training, using SQL Server and .NET Framework. He is an SEO professional too. He is capable of coordinating off-shore high level web development projects.






6 comments:

Gangstar15 said...

Very nice! thank you (:

Anonymous said...

It didn't work... :/

Utkarsh Yeolekar said...

It works for me .. Thank you so much.

Guri'qbal Sandhu said...

Thanks it worked

nitro said...

Well done. the only script that worked from more than half a dozen I tried. :)

nitro said...

Well done and thank you. Suited my need exactly and this was the first script to work from many that I tried before finding this page. :-))