提取属性参数中的值。

huangapple go评论79阅读模式
英文:

javascript: extract value from attribute parameter

问题

In JavaScript, to extract the value of 100 from the "transform" attribute in your SVG example, you can use the following code:

var tr_value = document.getElementById("g1").getAttribute("transform");
var match = tr_value.match(/translate\(([^ ]+) ([^ ]+)\)/);
if (match) {
  var xValue = parseFloat(match[1]);
  var yValue = parseFloat(match[2]);
  alert(xValue); // This will alert 100
}

This code uses a regular expression to match the "translate" function within the "transform" attribute and extracts the X and Y values from it. In your case, it will give you the value of 100 in the xValue variable.

英文:
<svg>
  <g id="g1" transform="translate(100 80)"/>
</svg>

<script>
  var tr_value = document.getElementById("g1").getAttribute("transform");
  alert(tr_value);   // result: translate(100 80)      need: 100
</script>

Hi to experts, tell me how to get the value of the attribute parameter in case the attribute has several parameters, and they, in turn, have several values. In the example above, I would like to get a value of 100 into a variable.
I really hope that in Javascript there is a beautiful method for this. And then the first thing that comes to mind is to parse text or regular expressions.

答案1

得分: 1

You'll have to write a regular expression or string parser to do this.

例如:.*\((\d*) \d*\)

.* - 任意字符序列
\( - 后跟开括号
( - 开始捕获组以匹配数组
\d* - 匹配任意数字序列
) - 结束捕获组
- 后跟一个空格
\d* - 后跟任意数字序列
\) - 后跟闭括号

注意:匹配的值将是一个字符串,如果您的代码期望的是数值,请进行类型转换。

英文:

You'll have to write a regular expression or string parser to do this.

e.g. .*\((\d*) \d*\)

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let tr_value = document.getElementById(&quot;g1&quot;).getAttribute(&quot;transform&quot;)
let regex = /.*\((\d*) \d*\)/g
let matches = regex.exec(tr_value)
console.log(matches[1]) // &quot;100&quot;

<!-- language: lang-html -->

&lt;svg&gt;
  &lt;g id=&quot;g1&quot; transform=&quot;translate(100 80)&quot;/&gt;
&lt;/svg&gt;

<!-- end snippet -->

.*\((\d*) \d*\) Regexplanation:

.* - Any sequence of characters
\( - followed by a open parenthesis
( - begin a capture group for matches array
\d* - match any sequence of numerical digits
) - end the capture group
- followed by a space
\d* - followed by any sequence of numeric digits
\) - followed by a close parenthesis

Note: the matched value will be a string, so you may need to cast it into a numeric value if that is what your code expects.

huangapple
  • 本文由 发表于 2020年1月7日 00:06:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/59615298.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定