Home > Net >  Get the integer value an attribute in a string in javascript
Get the integer value an attribute in a string in javascript

Time:05-21

I have a string that could look like these:

"length=10, width=40, height=80"
"length=10, height=80, width=40"
"width=40, height=80, length=10"

What's a quick way to parse a string to get the value of width no matter where it is in the string? Note that it can come at the end of the string or in the beginning/middle followed by a comma. So in the above example, the function should always return 40.

CodePudding user response:

This is the perfect use case for regular expressions. You want to match width=[0-9] but only capture the numeric part, so use a capturing group.

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions.

CodePudding user response:

You can use a regular expression for that.

For example: parseInt(/width=(\d )/i.exec(input)[1])

Or, the longer, more readable version:

const input = "length=10, width=40, height=80";
const regex = new RegExp("width=(\\d )", "i");

const result = regex.exec(input);

const width = parseInt(result[1]);

Alternatively, with a named capturing group:

const input = "length=10, width=40, height=80";
const regex = new RegExp("width=(?<width>\\d )", "i");

const result = regex.exec(input);

const width = parseInt(result.groups.width);
  • Related