Parsing strings for ints both Positive and Negative, Javascript

橙三吉。 提交于 2019-12-02 07:00:22

问题


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

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";
        }
  });

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.

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

Do any parseNinjas have any ideas? anything helps. Isaac


回答1:


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




回答2:


If you know what values you need to parse you could just multiply the negative ones by -1

Example:

num = -1 * (parseInt(matches[index], 10));


来源:https://stackoverflow.com/questions/11874136/parsing-strings-for-ints-both-positive-and-negative-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!