解析正整数和负整数的字符串,Javascript [英] Parsing strings for ints both Positive and Negative, Javascript

查看:101
本文介绍了解析正整数和负整数的字符串,Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在研究d3中的标签云示例.

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

并且试图将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.

此transform属性是我需要解析的字符串,但是该字符串包含我需要获取的正值和负值.

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.

这篇关于解析正整数和负整数的字符串,Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆