解析正负整数的字符串,Javascript

2022-01-18 00:00:00 position parsing d3.js tags javascript

所以我正在研究一个用 d3 制作的标签云示例.

So I am working through a tag cloud example made in d3.

http://www.jasondavies.com/wordcloud/#http%3A%2F%2Fsearch.twitter.com%2Fsearch.json%3Frpp%3D100%26q%3D%7Bword%7D=cloud

并且我试图在每个单词悬停时将 Div 放置在它的顶部,并且基本上遇到了问题,因为我放置 div 的方式取决于 svg word 元素的 transform 属性.

and am trying to position a Div ontop of each word when it is hovered over, and am basically having a problem because the way I am placing the div is dependent on the transform attribute of the svg word element.

这个转换属性是一个我需要解析的字符串,但是这个字符串包含了我需要抓取的正值和负值.

This transform attribute is a string I need to parse, but the string includes both positive AND negative values that I need to grab.

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.问题是它不会抓住负号.

My code is as above, where the last statement does nothing, but it is able to grab an Int from the string. The problem is that it won't grab the negative sign.

我不是最擅长解析,但我尝试了几个不同的 str.match 函数,但似乎没有任何效果.

I am not the best at parsing, but I have tried a couple different str.match functions and nothing seems to work.

任何 parseNinjas 有什么想法吗?任何事情都有帮助.艾萨克

Do any parseNinjas have any ideas? anything helps. Isaac

推荐答案

你的正则表达式应该是/-?d+/g,基本上是添加可选-"到模式.

Your regex should be /-?d+/g, basically adding "optional -" to the pattern.

相关文章