怎样才能使用jquery从文本中获取数字

Sur*_*ttu 18 javascript jquery

我想只得到数字(123)而不是文本(确认),这是我的代码

<p>123confirm</p>

<script type="text/javascript">
$(document).ready(function(){  
  $('p').click(function(){  
    var sd=$(this).text();  
    alert(sd);
  });
});  
</script>
Run Code Online (Sandbox Code Playgroud)

mfe*_*eis 36

我认为RegExp是个好主意:

var sd = $(this).text().replace(/[^0-9]/gi, ''); // Replace everything that is not a number with nothing
var number = parseInt(sd, 10); // Always hand in the correct base since 010 != 10 in js
Run Code Online (Sandbox Code Playgroud)

  • 答案中的正则表达式应该没问题,不需要明确指定每个数字:) (5认同)

jVa*_*ron 23

您可以使用parseInt它,它将解析一个字符串并删除其中的任何"垃圾"并返回一个整数.

正如James Allardice所注意到的那样,数字必须在字符串之前.因此,如果它是文本中的第一件事,它将起作用,否则它将不起作用.

- 编辑 - 与您的示例一起使用:

<p>123confirm</p>

<script type="text/javascript">
$(document).ready(function(){  
  $('p').click(function(){  
    var sd=$(this).text();  
    sd=parseInt(sd);
    alert(sd);
  });
});  
</script>
Run Code Online (Sandbox Code Playgroud)

  • 仅当数字出现在任何无效字符之前时(例子中的情况).例如"confirm123"将返回"NaN". (5认同)

Sal*_*Sal 5

您也可以使用以下方法:

$(document).ready(function(){  
  $(p).click(function(){  
    var sd=$(this).text();
    var num = sd.match(/[\d\.]+/g);
    if (num != null){
        var number = num.toString();
        alert(number );
    }
  });
});  
Run Code Online (Sandbox Code Playgroud)