[英]how to get dynamic substring in javascript?
我有一个滚动动画,想获得到给定时间的过渡值。
const transform = document.getElementsByClassName('slideContainer')[0].style.transform;
例如,我得到以下值: translate(-2.51028%, 0%) translate3d(0px, 0px, 0px)
但我只想要-2.51028%
我怎么做?
您可以使用String.prototype.split()
:
let str = "translate(-2.51028%, 0%) translate3d(0px, 0px, 0px)" console.log(str.split("(")[1].split(",")[0]);
听起来您可能想使用正则表达式-它们是匹配字符串模式的好工具。 您可以匹配字符串的开头,然后匹配translate(
,然后在组中捕获尽可能多的非逗号字符。该组将包含您想要的子字符串:
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]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.