Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Javascript > Regex question for String.replace; match whitespace OR nothing

Reply
Thread Tools

Regex question for String.replace; match whitespace OR nothing

 
 
jwcarlton
Guest
Posts: n/a
 
      02-04-2011
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?
 
Reply With Quote
 
 
 
 
Martin Honnen
Guest
Posts: n/a
 
      02-05-2011
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/
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Regex to match all trailing whitespace _and_ newlines. Dotan Cohen Python 2 10-10-2011 10:23 PM
regex match on nothing John Perl Misc 3 03-05-2010 07:24 AM
Structure using whitespace vs logical whitespace cmdrrickhunter@yaho.com Python 10 12-16-2008 03:51 PM
Whitespace where I don't want whitespace! Oli Filth HTML 9 01-17-2005 08:47 PM
Java regex can't match lengthy match? hiwa Java 0 01-29-2004 10:09 AM



Advertisments
 



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57