SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Jan 2002
    Posts
    9
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Javascript Replace Function...

    Hi
    I've been trying to gather some information together about a Replace function in javascript.
    I want to be able to type in some text in 1 text box then click a button and it will replace certain characters with others e.g. Replacing R and L with W (caps and no caps)

    Does anyone have a way i could do it??

    Thanxs in Advance!

    Christoph2k

  2. #2
    Web-coding NINJA! silver trophy beetle's Avatar
    Join Date
    Jul 2002
    Location
    Dallas, TX
    Posts
    2,900
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ya, the replace() function is most powerful when using regular expresssion syntax.
    The usage for replace() is like this:
    Code:
    str.replace(expression,replacement);
    expression is a string or a regular expression
    replacement is the string that is used to replace matches

    So, lets say you wanted to replace all lower/uppercase R's and L's with an uppercase W

    Code:
    var textStr = "Run Run Little Girl";
    
    textStr = textStr.replace(/[rRlL]/g,"W");
    The variable textStr now contains "Wun Wun WittWe GiWW"

    Without using regular expressions, you would need all this code to get the same result
    Code:
    textStr = textStr.replace("R","W");
    textStr = textStr.replace("R","W");
    textStr = textStr.replace("L","W");
    textStr = textStr.replace("l","W");
    textStr = textStr.replace("r","W");
    textStr = textStr.replace("l","W");
    Whew! AS you can see, without using regular expressions, we have to add one replace line for each letter!
    beetle a.k.a. Peter Bailey
    blogs: php | prophp | security | design | zen | software
    refs: dhtml | gecko | prototype | phpdocs | unicode | charsets
    tools: ide | ftp | regex | ffdev




  3. #3
    Perl/Mason Guru Flawless_koder's Avatar
    Join Date
    Feb 2002
    Location
    Gatwick, UK
    Posts
    1,206
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Regular expressions are an extremely powerful tool
    in programming ( note me being a perl guy ).
    I think that O'Reilly have an absolutely great book
    on Mastering regular expressions which goes through
    the more complex notions of how regex works.

    Only if you're interested...

    Flawless
    ---=| If you're going to buy a pet - get a Shetland Giraffe |=---


Bookmarks

Posting Permissions

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