Regex question for String.replace; match whitespace OR nothing

J

jwcarlton

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?
 
M

Martin Honnen

jwcarlton said:
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.
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top