Parsing strings for ints both Positive and Negativ

2020-04-19 09:40发布

问题:

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