Ic3m4n
Ic3m4n

Reputation: 871

how to get dynamic substring in javascript?

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?

Upvotes: 0

Views: 281

Answers (2)

connexo
connexo

Reputation: 56843

You could use String.prototype.split():

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

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

Upvotes: 4

CertainPerformance
CertainPerformance

Reputation: 371193

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]);

Upvotes: 1

Related Questions