1

I have a string like .hello-world-chat-size {height: 350px !important;} and I want to extract the value of height attribute i.e 350. I tried this regex /^height\:(.*)$/gm but cant get any result.

iamsaksham
  • 2,879
  • 4
  • 26
  • 50
  • Because `^` matches the start of string and `$` matches the end of string. You can just use `/height:\s*(\d+)px/`, or anything similar. – Wiktor Stribiżew Jul 15 '16 at 14:02
  • 1
    out of curiosity, if you want an attribute of an element, why not just grab that instead of regex a string? (offsetHeight or clientHeight http://stackoverflow.com/questions/15615552/get-div-height-with-plain-javascript) – Nikki9696 Jul 15 '16 at 14:03
  • 1
    @Nikki9696 I have extracted the above string using `getElementsByTagName().innerHTML` so it is a string – iamsaksham Jul 15 '16 at 14:05
  • 1
    It's usually better to use the DOM if you can, and you do have the element in the DOM if you used getElementsByTagName. Just a suggestion. Happy Friday! =) "Some people, when confronted with a problem, think "I know, I'll use regular expressions." Now they have two problems." https://blog.codinghorror.com/regular-expressions-now-you-have-two-problems/ – Nikki9696 Jul 15 '16 at 14:11
  • Yah,, U are correct. I'll research getElementsByTagName a bit and will try to eliminate the regex. – iamsaksham Jul 15 '16 at 14:23

1 Answers1

1

The issue occurs because ^ matches the start of string and $ matches the end of string. Actually, (.*)$ matches the whole rest of the line, but since the beginning of the pattern did not match, there was no match at all. You can just use

/height:\s*(\d+)px/

or

/height:\s*(\d+)/

See the regex demo

Details:

  • height: - a literal substring height:
  • \s* - zero or more whitespace symbols
  • (\d+) - 1 or more digits
  • px - a literal string px (actually, it is redundant, but just in case you might have other value without px, you might keep it to be as explicit as can be)

JS demo:

var re = /height:\s*(\d+)px/; 
var str = '.hello-world-chat-size {height: 350px !important;}';
var m = str.match(re);
if (m) {
  console.log(m[1]);
}
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • what about `.equal-height-div {width:123px;}`? – Alex Kudryashev Jul 15 '16 at 14:27
  • That is a bit different, what do you want to extract from it? `123`? A mere `/width:(\d+)/` will do. Add more context for a safer match. Say, you can add `{`: `/{width:(\d+)/`. Or if there can be whitespaces: `/{\s*width\s*:\s*(\d+)/` – Wiktor Stribiżew Jul 15 '16 at 14:34