Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • replace() method in JavaScript

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 117
    Comment on it

    JavaScript String replace() method : The replace() method is used to replace a string from new value. The replace() method has two parameters, first parameter is a string or regular expression which need to be replace by new value and the second parameter is the new value.


    Syntax of replace() method :

    string.replace(search-value, new-value)
    

    Description

    search-value - This is required. This can be string of a regular expression which need to be search.

    new-value - This is required parameter. This is the new string which will replace the old or matching string.


    Example 1 : Following is the example of replace() method. In this example we perform the global repacement of string (case-sensitive):

    <!DOCTYPE html>
    <html>
    <body>
    <p>Click the button to replace "is" with "was" in the word below:</p>
    <p id="container">He is a great person.Is it fine?</p>
    <button onclick="replaceString()">replace</button>
    
    <script>
    function replaceString() {
        var val = document.getElementById("container").innerHTML; 
        var result = val.replace(/is/g, "was");
        document.getElementById("container").innerHTML = result;
    }
    </script>
    
    </body>
    </html>
    
    Output : He was a great person.Is it fine?
    

    In the above example you can see that is is replaced with the was but Is is not replaced because it is case-sensitive.


    Example 2 : In this example I will show you that how you can search and replace the string without thinking about case. Here is the case-insensitive example:

    <!DOCTYPE html>
    <html>
    <body>
    
    <p>Click the button to replace "is" with "was" in the word below:</p>
    <p id="container">He is a great person.Is it fine? </p>
    <button onclick="replaceString()">replace</button>
    
    <script>
    function replaceString() {
    
        var val = document.getElementById("container").innerHTML; 
        var result = val.replace(/is/gi, "was");
        document.getElementById("container").innerHTML = result;
    }
    </script>
    </body>
    </html>
    
    Output : He was a great person.was it fine?
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: