RegEx noob question

Discussion in 'Javascript' started by neptune6jun44, Sep 19, 2008.

  1. I need to take a string and allow only the first occurrence of an
    apostrophe for the validation of a city name...

    Example: D'Iberville, MS

    Say someone enters D'I'berville, MS by mistake..

    I'm able to retain all the apostrophes with the following:


    I want to retain the first apostrophe only. I've tried adding {2,} in
    with the apostrophe, but no luck.

    An example of the proper way to do this would be greatly appreciated.

    neptune6jun44, Sep 19, 2008
    1. Advertisements

  2. neptune6jun44

    Kiran Makam Guest

    In string replace method, second parameter can be a function. You can
    make use of this like:
    var str = "D'I'ber'v'i'lle";
    var myRe = /([^']*')(.*)/;

    str = str.replace(myRe,
    function (matchStr, strInParanthesis1, strInParanthesis2) {
    return strInParanthesis1 + strInParanthesis2.replace(/'/g,

    "D'I'ber'v'i'lle" will become "D'Iberville"
    "'DIber'v'i'lle" will become "'DIberville"

    - Kiran Makam
    Kiran Makam, Sep 19, 2008
    1. Advertisements

  3. S = "1'2'3'4'5"
    S.replace("'", "\xFF").replace(/'/g, "").replace("\xFF", "'")

    There, \xFF can be replaced by any chatacter that cannot occur in the

    S = "1'2'3'4'5"
    P = S.indexOf("'")
    S = S.substring(0,P+1) + S.substring(P+1).replace(/'/g, "")
    Dr J R Stockton, Sep 20, 2008
  4. I think this would be the most efficient, yes. If there were a single
    regex, it would go like this:




    But javascript only supports look-ahead (?=/?!) and not look-behind (?
    <=/?<!); so there is no other choice than finding a workaround. It
    already struck me a few times that javascript has some gaps in the
    language: no regex look-behind, no reverse()-property for strings, ...
    Bart Van der Donck, Sep 21, 2008
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.