Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Jul 2012
    Posts
    2
    Thanks
    1
    Thanked 0 Times in 0 Posts

    How can I replace the text in an input field?

    The replace method only works on a string with the first match substring. In the below example, how can I replace all 'a' with 'b'? Thanks in advance for any help!

    Code:
        <script>
    function replaceIt(){
    	var textStore = document.getElementById("textInput").value;	
    	var newText = textStore.replace("a","b");
    	alert(newText);
    };
    	</script>
        
    
       
    <input value="aaaabbbccc" type="text" id="textInput" name="textInput" />
    <button onclick="replaceIt()">Replace all the a with b!</button>
    Last edited by dennisboys; 07-18-2012 at 08:12 AM.

  • #2
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    17,917
    Thanks
    203
    Thanked 2,531 Times in 2,509 Posts
    Code:
    <script type = "text/javascript">
    
    function replaceIt(){
    var textStore = document.getElementById("textInput").value;	
    var newText = textStore.replace(/a/gi,"b");  // g means global, i means ignore case
    alert(newText);
    }
    </script>
           
    <input value="aaaabbbccc" type="text" id="textInput" name="textInput" />
    <button onclick="replaceIt()">Replace all the a with b!</button>

    Quizmaster: What is the last letter of the Greek alphabet?
    Contestant: Zulu

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • Users who have thanked Philip M for this post:

    dennisboys (07-18-2012)

  • #3
    New to the CF scene
    Join Date
    Jul 2012
    Posts
    2
    Thanks
    1
    Thanked 0 Times in 0 Posts
    Thank you Philip!! im new to here and im so glad that i get a response so quickly in the forum.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •