0

I have a scroll animation and want to get the transition value to a given time.

const transform = document.getElementsByClassName('slideContainer')[0].style.transform;

For example I get the following value: translate(-2.51028%, 0%) translate3d(0px, 0px, 0px)

But I just want the -2.51028%

How do I do that?

2 Answers 2

4

You could use String.prototype.split():

let str = "translate(-2.51028%, 0%) translate3d(0px, 0px, 0px)"

console.log(str.split("(")[1].split(",")[0]);

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

Comments

1

Sounds like you might want to use a regular expression - they're great tools for matching patterns in strings. You can match the start of the string, followed by translate(, then capture as many non-comma characters as you can in a group. That group will have the substring you want:

const transform = 'translate(-2.51028%, 0%) translate3d(0px, 0px, 0px)';
const match = transform.match(/translate\(([^,]+)/);
// match[0] refers to the entire matched substring,
// match[1] will contain the first captured group:
console.log(match[1]);

1 Comment

So many people just hate regexes :). I wish I was better at it though...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.