所以我正在研究一个用 d3 制作的标签云示例。
我试图在悬停时将 Div 定位在每个单词的顶部,但我基本上遇到了问题,因为我放置 div 的方式取决于 svg 单词元素的 transform 属性。
此转换属性是我需要解析的字符串,但该字符串包括我需要抓取的正值和负值。
tagCloudHover.style("top", function(){
//parses the words attributes for its position, and gives that position to tagCloudHover
var str, matches, index, num;
str = thisWord.attr("transform");
matches = str.match(/\d+/g);
for (index = 1; index < 2; ++index) {
num = (parseInt(matches[index], 10));
}
if(num<0){
return -num+"px";
}else{
return num+"px";
}
});
我的代码如上,最后一条语句什么都不做,但它能够从字符串中获取一个 Int。问题是它不会捕获负号。
我不是最擅长解析的,但我尝试了几个不同的 str.match 函数,但似乎没有任何效果。
parseNinjas 有什么想法吗? 任何帮助。 艾萨克
最佳答案
你的正则表达式应该是 /-?\d+/g
,基本上是在模式中添加“optional -
”。
关于javascript - 为正负整数解析字符串,Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11874136/