Jquery search and replace

This Comment will be submitted for moderation and will not be accessible to other users until it has been approved.


5 points

Hi Guys,

I need a jquery code where I need to search for an element and then replace every period (\.) with the text "[this is period]". How can I do this jquery search and replace?



5 points

You need to use Jquery replace() API function:

var e = $('#container').text();
e.replace(/\./g, "[this is period]");

Jquery replace() takes first argument as the regular expression. So, the code below means that we are trying to replace all (/g) occurrence of text in #container with the text.

e.replace(/\./g, "[this is period]");

Therefore, the complete JQuery code looks like this:

<!DOCTYPE html>
<html>
<head>
 
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
	<div id="container">
This is test for JQuery Find and Replace. This should work correctly.
 
<script>
var e = $('#container').text();
e.replace(/\./g, "[this is period]");
</script>
</body>
</html>

This would give output:

This is test for JQuery Find and Replace[this is period] This should work correctly[this is period]

Anonymous's picture
Created by Anonymous
4 points

Really Awesome and Thanks

Anonymous's picture
Created by Anonymous

Post Comment

  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <php>, <python>, <ruby>. Beside the tag style "<foo>" it is also possible to use "[foo]". PHP source code can also be enclosed in <?php ... ?> or <% ... %>.