英文:
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("g1").getAttribute("transform")
let regex = /.*\((\d*) \d*\)/g
let matches = regex.exec(tr_value)
console.log(matches[1]) // "100"
<!-- language: lang-html -->
<svg>
<g id="g1" transform="translate(100 80)"/>
</svg>
<!-- 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论