Results 1 to 3 of 3

Thread: replace all

  1. #1

    Thread Starter
    Hyperactive Member
    Join Date
    Jan 2002
    Posts
    259

    replace all

    How can I replace A With B in the string:

    I used this JavaScript code:

    var Y=X.replace('A','B');

    but it is replace one letter only from the string ... I want to replace all A with B.

  2. #2
    Addicted Member
    Join Date
    Nov 2001
    Location
    Liverpool, England
    Posts
    155
    Code:
    <html>
    <head>
    <title>Untitled</title>
    
    <script>
    
    function foo(inStr) {
    inStr = inStr.replace(/a/gi, 'b');
    alert(inStr);
    }
    
    </script>
    
    </head>
    <body>
    <input type="button" value="Test" onClick="foo('abc abc abc');">
    </body>
    </html>

  3. #3
    Hyperactive Member progressive's Avatar
    Join Date
    Sep 2001
    Location
    Manchester, UK
    Posts
    404
    As with the previous question about match() you need to use a regex with replace().

    eg:
    Code:
    var my_string = "abbAa";
    my_string.replace(/a/, 'b');
    
    //mystring now equals "bbbAa"
    however this will only replace on occurence of a lower case 'a'
    so you need to use two regex commands
    g - global replace, replaces all occurence of the regex in the string.
    i - ignor case, replaces upper and lowercase

    so the finished statement should be:
    Code:
    var my_string = "abbAa";
    my_string.replace(/a/gi, 'b');
    
    //mystring now equals "bbbbb"
    I recommend you get yourself a good regex book as they are invaluable in many web scripting languages such as Perl, PHP, and javascript and the syntax is very similar for all.


Posting Permissions

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



Click Here to Expand Forum to Full Width