SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Zealot
    Join Date
    Jul 2002
    Location
    Fort Lauderdale
    Posts
    123
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Regular expression, replace all

    Code:
    str = "1x2_3 4";
    str2 = str.replace(/\D/, "");
    This will replace the x, but I want to replace all non-numerics. I am looking for the most efficient way(I don't want a loop).
    Thanks.

    www.unpossiblemedia.com - A Fort Lauderdale based multimedia company.

  2. #2
    SitePoint Addict
    Join Date
    May 2000
    Posts
    313
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Here is an example of one way you could do it:
    <html>
    <head>
    <title>Regulare Expressions</title>
    <script language="JavaScript">

    re1=/\D/g
    function checkval()
    {
    myvar1=document.myform.num1.value
    myvar2=myvar1.replace(re1,"")
    document.myform.num1.value=myvar2
    }
    </script>
    </head>
    <body>
    <form name="myform">
    <input type="text" name="num1" size="11" maxlength="11">
    <input type="button" value="Enter something" onClick="checkval()">
    </form>
    </body>
    </html>

  3. #3
    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)
    You just need the global pattern modifer

    str2 = str.replace(/\D/g, "" );

    Otherwise, it will only replace the first match, as you have seen

    I know requestcode already posted this, but I'm not sure if it was totally clear to you.
    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




  4. #4
    SitePoint Zealot
    Join Date
    Jul 2002
    Location
    Fort Lauderdale
    Posts
    123
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks, exactly what I was looking for.

    www.unpossiblemedia.com - A Fort Lauderdale based multimedia company.


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
  •