0

I have this code

htmlString= htmlString.replace( new RegExp( "WW(.+?)WW", "gim" ),
    "<span style='color:red;border-bottom:1px dashed red;'>$1</span>" );

This seems to work however it is replacing the www's in url's. What I have is WW somestring WW I clip out the text between WW and replace it. However, I can't seem to only get the exact char sequence. I tried {WW} ^WW [^WW] with the end [$WW] and variations. Also tried \bWW string \bWW and no match.

Any help would be great, thanks.

4
  • 1
    Give more examples of what you are trying to replace. Commented May 24, 2011 at 15:50
  • Wouldn't a regex literal look better? Commented May 24, 2011 at 15:51
  • Sample string = PHysell WW 3 miles Northwest Christiansburg, va WW Pea size hail Commented May 24, 2011 at 15:53
  • WW ---- WW is the designator that there is some location in between. Could be named location, state, zipcode, intersection, etc. Commented May 24, 2011 at 15:54

2 Answers 2

4

Assuming that there is something else than alphanumeric characters after the starting WW and before the ending WW (whitespace, for example), then you could do this:

htmlString = htmlString.replace(/\bWW\b\s*(.+?)\s*\bWW\b/g, 
    "<span style='color:red;border-bottom:1px dashed red;'>$1</span>" );

Using a regex object instead of a string literal makes it easier to read. If you had used \b in a string literal it would have meant "backspace" - you need to escape backslashes in a string literal, so the above regex would become "\\bWW\\b\\s*(.+?)\\s*\\bWW\\b".

Sign up to request clarification or add additional context in comments.

1 Comment

BAM thanks, that does look better. I tried the \b but didn't add the / to the beginning or something. I will get the hang of this regex someday. Thanks again.
0

If the text you're looking to replace is always uppercase and the www you don't want to replace is always lowercase, then you can just replace the "gim" with "gm": the i indicates ignore case. The m in "gim" has no meaning in a RegExp so you can reduce to "g".

2 Comments

Well I cant assume it will always be upper or lowercase. Should be upper but users make errors. However that would be a quick fix in the mean time, thanks.
What about the spaces on either side of 'WW'... are those required? If so, your search can be " WW (.+?) WW " and you can ignore case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.