jQuery ReplaceAll method

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<!DOCTYPE html>
<html>
<head>
  <title>jQuery ReplaceAll</title>
 
  <!-- Reference: http://www.jquerywithexample.com/2013/03/replace-string-in-jquery.html -->

 
  <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 is friend of India>')); //back slash to escape characters
        alert(country.replace(/india/gi, 'japanese'));
        alert(country.replace(/\./g, 'japan'));
      });
    });
  </script>
</head>
<body>

If you simply use this method, it will replace the only first matches string. </br>
If you use (/g) with replace method, it will replace all case sensitive matches string. </br>
If you use (/gi) with replace method, it will replace all matches string.</br>
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.
  <div>
    <input type="button" id="btnClick" value="Click Here" />
  </div>
</body>
</html>

No comments:

Post a Comment