Marcy Thompson
Marcy Thompson

Reputation: 31

Javascript RegEx - I want to match a pattern other than the first occurance

I want to convert this:

.className#lets.par.ty

To this:

.className[id="lets"][class="par"][class="ty"]

I don't want to alter the first instance of the "."

Here is what I came up with but I know it is absolutely NOT ideal:

cssOutput[i] = cssOutput[i]
.replace (/^#/,'?') // convert all start ids to ?    
.replace (/#([^\.#]+)/g,'[id="$1"]') // insert [id=""]
.replace (/\?/g,'#') // convert all start ? back to ids
.replace (/^\./,'?') // convert all start classes to ?   
.replace (/\.([^\.#]+)/g,'[class="$1"]') // insert [class=""]
.replace (/\?/g,'.') // convert all start ? back to classes

Can anyone help?

Upvotes: 0

Views: 158

Answers (2)

Alan Moore
Alan Moore

Reputation: 75272

You can invert the anchor's meaning by enclosing it in a negative lookahead:

s = s.replace(/(?!^)\.(\w+)/g, '[class="$1"]')
     .replace(/(?!^)#(\w+)/g,  '[id="$1"]');

See it in action on ideone.

Upvotes: 1

Bart Kiers
Bart Kiers

Reputation: 170308

Try:

var s = ".className#lets.par.ty";
s = s.replace(/\.(\w+)#(\w+)\.(\w+)\.(\w+)/, '.$1[id="$2"][class="$3"][class="$4"]');

A demo: http://ideone.com/51XkY

EDIT

To skip the first first character of the input, simply do something like this:

var tests = ['.className1', '#className2', '.className.class1#class2#class3'];

for(var index in tests) {

  var t = tests[index];

  t = t.charAt(0) + t.substring(1).
      replace(/\.(\w+)/g, '[class="$1"]').
      replace(/#(\w+)/g,  '[id="$1"]');

  print(t);
}

which produces:

.className1
#className2
.className[class="class1"][id="class2"][id="class3"]

Test it online here: http://ideone.com/YmJGu

Upvotes: 4

Related Questions