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="" >
<title>Replace Word in a Text using jQuery</title>
<script type="text/javascript"
   2:      <script type="text/javascript" language="javascript">
   3:          $(function () {
   4:              $("#btnReplace").click(function () {
   5:                  $("#div1").html($("#div1").html().replace("aamir", "Aamir Hasan"));
   6:              });
   7:          }); 
<div id="div1">My name is aamir</div><br />
<input id="btnReplace" type="button" value="Replace" />


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.

Will you give this article a +1 ? Thanks in advance


Gangstar15 said...

Very nice! thank you (:

Anonymous said...

It didn't work... :/

Utkarsh 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. :-))