#1
  1. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2008
    Posts
    369
    Rep Power
    55

    Question Javascript replace


    I have text which can look like any of these:

    5 (53.52)
    25(2.35)
    Hello (6.25)

    I need to, in javascript, get the text inside of the parentheses. The rest is garbage. I know how to match the text with a regex, but not find it for use in .replace();

    Perhaps there is a better method then .replace for this? Any help would be greatly appreciated.
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2008
    Posts
    369
    Rep Power
    55
    I guess I could use match

    Code:
    txt = string.match('/\(.*?\)/');
    Although that regex returns null
  4. #3
  5. CSS & JS/DOM Adept
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jul 2004
    Location
    USA (verifiably)
    Posts
    20,128
    Rep Power
    4304
    That code snippet isn't working as you expect because the forward slashes are used literally because it's a string, so it's silently being converted to a regexp object.

    I might do it like this: (the join, replace, and split method calls are to remove the parentheses.)
    Code:
    txt = string.match(/\([^\(\)]+\)/g).join('').replace(/\(|\)$/g,'').split(/\)/);
    Spreading knowledge, one newbie at a time.

    Check out my blog. | Learn CSS. | PHP includes | X/HTML Validator | CSS validator | Common CSS Mistakes | Common JS Mistakes

    Remember people spend most of their time on other people's sites (so don't violate web design conventions).

IMN logo majestic logo threadwatch logo seochat tools logo