开发者

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

开发者 https://www.devze.com 2023-01-24 09:45 出处:网络
I want to convert this: .className#lets.par.ty To this: .className[id=\"lets\"][class=\"par\"][class=\"ty\"]

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?


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号