Regex question for String.replace; match whitespace OR nothing

Discussion in 'Javascript' started by jwcarlton, Feb 4, 2011.

  1. jwcarlton

    jwcarlton Guest

    I have a section that may, or may not, include a whitespace. Like
    this:

    var string = "<b><p>Jason</p> </b>";

    I'm wanting to do this:

    string = string.replace(/<b><p>jason<\/p> <\/b>/gi, "Jason");

    But the problem is that the whitespace between </p> and </b> might NOT
    exist. I'm doing it like this, but I know that it's wrong because it
    would find anything, not just a whitespace:

    string = string.replace(/<b><p>jason<\/p>(.*)<\/b>/gi, "Jason");

    I'm pretty sure that this isn't right, but it's the direction I was
    going:

    string = string.replace(/<b><p>jason<\/p>(\s*|(.)*?)<\/b>/gi,
    "Jason");


    What's the correct way to match a whitespace, or nothing?
     
    jwcarlton, Feb 4, 2011
    #1
    1. Advertising

  2. jwcarlton wrote:
    > I have a section that may, or may not, include a whitespace. Like
    > this:
    >
    > var string = "<b><p>Jason</p> </b>";
    >
    > I'm wanting to do this:
    >
    > string = string.replace(/<b><p>jason<\/p> <\/b>/gi, "Jason");
    >
    > But the problem is that the whitespace between</p> and</b> might NOT
    > exist. I'm doing it like this, but I know that it's wrong because it
    > would find anything, not just a whitespace:
    >
    > string = string.replace(/<b><p>jason<\/p>(.*)<\/b>/gi, "Jason");
    >
    > I'm pretty sure that this isn't right, but it's the direction I was
    > going:
    >
    > string = string.replace(/<b><p>jason<\/p>(\s*|(.)*?)<\/b>/gi,
    > "Jason");
    >
    >
    > What's the correct way to match a whitespace, or nothing?


    Well if you expect a single space or no space then use
    /<b><p>jason<\/p> ?<\/b>/gi
    or if you expect any white space then use
    /<b><p>jason<\/p>\s*<\/b>/gi
    But as one of your samples already uses \s I am not sure I understand
    what problem you face.


    --

    Martin Honnen
    http://msmvps.com/blogs/martin_honnen/
     
    Martin Honnen, Feb 5, 2011
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Dotan Cohen
    Replies:
    2
    Views:
    514
    Dotan Cohen
    Oct 10, 2011
  2. John Gordon
    Replies:
    13
    Views:
    490
    Ian Kelly
    Dec 20, 2011
  3. Devin Jeanpierre
    Replies:
    2
    Views:
    468
    Devin Jeanpierre
    Feb 14, 2012
  4. Replies:
    3
    Views:
    175
    Brian McCauley
    Sep 12, 2005
  5. John

    regex match on nothing

    John, Mar 4, 2010, in forum: Perl Misc
    Replies:
    3
    Views:
    131
Loading...

Share This Page