0

Is there a quick way or predefined JavaScript method that converts

"text-align"
"-webkit-transform"
"position"
"background-image"

into

"textAlign"
"webkitTransform"
"position"
"backgroundImage"

with vanilla javascript (no jQuery, ect)?

1
  • Whilst I'm not aware of a method to do so, it should be a fairly trivial job with a regex replace if the rules are assumed to just be "remove initial hyphen if present, and remove subsequent hyphens and capitalise the following letter" Commented Oct 28, 2014 at 17:25

2 Answers 2

4

Use this regex replace:

"text-align".replace(/-([a-z])/g,function(m,l,i){return i?l.toUpperCase():l})

It matches a hyphen and then a letter. The replace returns the letter, capitalized if the index is truthy (not 0).

Sign up to request clarification or add additional context in comments.

2 Comments

+1 Couldn't think of a quick way of removing the first hypen without altering the following character
The accepted answer from @Issac did not work for me in latest Chrome. The conversion rule is as easy as the solution in this answer.
0

After hunting around I found that the variable I was dealing with was of type CSSStyleDeclaration which comes with a method getPropertyCSSValue

Simplified extract

var rules = document.styleSheets[0/*sheetIndex*/].rules[0/*ruleIndex*/];
console.log(rules.toString()); // "[object CSSStyleRule]"
for(var a = 0; a<rules.style.length; a++)
{
  var rule = rules.style[a];
  console.log(rule,rules.style.getPropertyCSSValue(rule).cssText); // eg: "text-align","center"
}

This avoids issues with "border" and "border-left"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.