簡體   English   中英

如何在javascript中獲取動態子字符串?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM