Welcome to WebmasterWorld Guest from 54.146.206.127

Forum Moderators: open

Message Too Old, No Replies

JavaScript replace string patterns

RegExp question

     
7:49 pm on Sep 2, 2003 (gmt 0)

Junior Member

10+ Year Member

joined:Apr 16, 2003
posts:110
votes: 0


I have a working replace function

function fixcode(clean) {
clean = clean.replace(/<\/font>/gi, '</span>');
return unclean; }

but I need to look for patterns for example:


If: <font span="foo">Hello</font>
To: <span class="foo">Hello</span>

If: <font face="foo">Hello</font>
To: no change


It's just a simple RegExp but I can't figure out the syntax.
Any Ideas?
8:28 pm on Sept 2, 2003 (gmt 0)

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:July 26, 2003
posts:881
votes: 0


I think you have to use a parenthetical and backreference it...

function fixcode(input) {
input = input.replace(/<font span=([^<]+)<\/font>/gi, "<span class=$1</span>");
return input;
}
function fixit() {
document.getElementsByTagName("body")[0].innerHTML = fixcode(document.getElementsByTagName("body")[0].innerHTML);
}

<body onload="fixit();">

I think I got that right...

Jordan

9:01 pm on Sept 2, 2003 (gmt 0)

Junior Member

10+ Year Member

joined:Apr 16, 2003
posts:110
votes: 0


It works MonkeeSage saves the day!

Darn blasted Regular Expressions won't leave me alone.

9:20 pm on Sept 2, 2003 (gmt 0)

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:July 26, 2003
posts:881
votes: 0


I know how you feel about regexps, lol, I'm learning them myself and it is slow going at times. ;)

The key to the pattern is the stuff in the parentheses:

([^<]+)

This means...
1. () - Put the match into a "group" that we can call back on in the replacement string using the number of the group (e.g., $1).
2. [] - Special match that will use multiple characters as a rule (e.g., ^<).
3. ^ - Match anything that is not the character that follows this one (e.g., <).
4. + - Find at least one occurance of the special match, and include all characters in the match.

So it ends up matching '<font span=("foo">Hello)</font>' with '"foo">Hello' able to be inserted into the replace string using $1.

Jordan

1:02 am on Sept 3, 2003 (gmt 0)

Junior Member

10+ Year Member

joined:Apr 16, 2003
posts:110
votes: 0


Very nice little mini tutorial that helps clear it up.

By the way this worked too.
.replace(/<font class="([^"]+)"(.*?)<\/font>/gi, "<span class=\"$1\"$2</span>");