开发者

Ruby String manipulation of HTML Element IDs

I'm looking for a safe way of building a string of a HTML element id from another element id.

I need to go from something like "attr_name_442_a" to "attr-row-422", the text part of the ids are consistent with just the number changing. This number will be in the range of 1 to开发者_如何学编程 4 digits.

I thought of doing this but is there a better Ruby style method?

newID = oldID.gsub("_","-").gsub("name","row").gsub("-a","")


You may be able to pull this off with a single Regex

newID = oldID.gsub /(\w+)_name_(\d+)_a/, '\1-row-\2'


new_id = "#$1-row-#$2" if $old_id =~ /\A([^_]+)_name_(\d{1,4})_a\z/

I would probably add an else condition if the regex didn't match just so I knew I was catching everything.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜