Forum Moderators: open

Message Too Old, No Replies

Regular Expression request

         

Bernard Marx

5:36 pm on Nov 26, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Who's up to this simple task that has so far foxed me?

I'd like 2 REs (and accompanying replacement expressions)
1. Turns CSS syntax for property names into Javascript syntax:

border-left-color // upper,lower or mixed case
--> borderLeftColor

2. The reverse, with the result in lower-case.

Oh, and the replacement expression cannot be a function.

DrDoc

6:56 pm on Nov 26, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Well, there are several problems with a task like this... First off, something like the following would seem to make sense:

CSS = 'border-left-color';
CSStoJS = CSS.replace(/(-[a-z])/g,'$1'.substring(1).toUpperCase());

However, it's not that simple, despite the fact that

CSS.replace(/(-[a-z])/g,'$1')
would return the string as it was prior to replacement.

But, once you start modifying the matched pattern, well, JavaScript will first do all the modifications, then replace

$1
with the pattern match. In other words, the example above would return
border1eft1olor
! Extremely backwards :(

Throwing in a couple

eval()
doesn't help either. Neither would passing the matched pattern to a function.

In order to do what you want, you are forced (by the sheer backward nature of pattern matches in JavaScript) to use two separate regular expressions -- one to extract the pattern matches, and one to do the replacement. The reason for this is that the pattern match gets written to an element in an array as a plain text string. Thus, when you do any modifications on the string, it has already been deassociated with any pattern it matched.

So, the following would work:

<script type="text/javascript">
CSS = 'border-left-color';
JS = 'borderLeftColor';

matches = CSS.match(/(-[a-z])/g);
CSStoJS = CSS.toLowerCase();
for(i=0;i<matches.length;i++) {
regexp = new RegExp(matches[i])
CSStoJS = CSStoJS.replace(
regexp,
matches[i].substring(1).toUpperCase()
);
}
alert(CSStoJS);

matches = JS.match(/([A-Z])/g);
JStoCSS = JS;
for(i=0;i<matches.length;i++) {
regexp = new RegExp(matches[i])
JStoCSS = JStoCSS.replace(
regexp,
'-' + matches[i].toLowerCase()
);
}
alert(JStoCSS);
</script>

I know... not as pretty, but it does the job.