replace a string in jquery

Replace method is used to replace a string in jQuery, but it is little difference in compression of programming language.

If you simply use this method, it will replace the only first matches string.

If you use (/g) with replace method, it will replace all case sensitive matches string.

If you use (/gi) with replace method, it will replace all matches string.

Note: Replace functions returns a string which contains the updated text. It will not modify the current variable, So you need to re-assign it.

If you are only replacing (.) in a string, you need to make some change in the replace function arguments.

CODE
<!DOCTYPE html>
<html>
<head>
  <title>jQuery With Example</title>
  <script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
  <script type="text/javascript">
    $(function () {
      $('#btnClick').click(function () {
        var country = "india india INDIA .";
        alert(country.replace('india', 'japan'));
        alert(country.replace(/india/g, 'japan'));
        alert(country.replace(/india/gi, 'japan'));
        alert(country.replace(/\./g, 'japan'));
      });
    });
  </script>
</head>
<body>
  <div>
    <input type="button" id="btnClick" value="Click Here" />
  </div>
</body>
</html>
DISPLAY

3 comments :

  1. Too Much quality and good content on JQuery. I read and learn lot of from year.

    Thanks to Publisher Mr. Nirbhay Singh

    ReplyDelete
  2. Beautiful example! Simple and concise, and answered my question perfectly. Thx!

    ReplyDelete