I am trying to create a test in which I want to compare the width of an element after it has been resized by dragging it. The problem is that the resize library returns the width value as
JavaScript
x
2
1
calc(50% - 4px)
2
The only thing that changes is this percentage value and this is what I want to compare in the test if it is bigger or smaller depending on the mouse movement to the right or left.
However, I do not know how to extract only the percentage value or possibly the subtraction result from this string.
JavaScript
1
5
1
it("has resizable containers", async () => {
2
const initialRightWith = rightContainer.style.width;
3
expect(initialRightWith).toEqual("50%");
4
});
5
Expected: “50%” Received: “calc(50% – 4px)”
Advertisement
Answer
You could use a regular expression to get the percentage from your string, here’s an example:
JavaScript
1
10
10
1
const width = 'calc(50% - 4px)';
2
const regex = /^calc((d{1,3})%.+$/;
3
4
const getPercentageFromCalc = (w) => {
5
const matches = regex.exec(width);
6
7
return matches[1];
8
};
9
10
console.log(getPercentageFromCalc(width));
Remember to add checks to make sure your regular expression matched something, this is just an example!