我有一个JavaScript格式的字符串(例如#box2),我只想要其中的2.

我试过:

var thestring = $(this).attr('href');
var thenum = thestring.replace( /(^.+)(\w\d+\w)(.+$)/i,'$2');
alert(thenum);

它在alert 中仍然返回#box2,我怎么才能让它工作呢?

它需要适应末端附加的任何长度编号.

推荐答案

对于这个具体的例子,

 var thenum = thestring.replace( /^\D+/g, ''); // replace all leading non-digits with nothing

在一般情况下:

 thenum = "foo3bar5".match(/\d+/)[0] // "3"

由于某种原因,这个答案很受欢迎,这里有一个好处:正则表达式生成器.

function getre(str, num) {
  if(str === num) return 'nice try';
  var res = [/^\D+/g,/\D+$/g,/^\D+|\D+$/g,/\D+/g,/\D.*/g, /.*\D/g,/^\D+|\D.*$/g,/.*\D(?=\d)|\D+$/g];
  for(var i = 0; i < res.length; i++)
    if(str.replace(res[i], '') === num) 
      return 'num = str.replace(/' + res[i].source + '/g, "")';
  return 'no idea';
};
function update() {
  $ = function(x) { return document.getElementById(x) };
  var re = getre($('str').value, $('num').value);
  $('re').innerHTML = 'Numex speaks: <code>' + re + '</code>';
}
<p>Hi, I'm Numex, the Number Extractor Oracle.
<p>What is your string? <input id="str" value="42abc"></p>
<p>What number do you want to extract? <input id="num" value="42"></p>
<p><button onclick="update()">Insert Coin</button></p>
<p id="re"></p>

Javascript相关问答推荐

如何在不使用类型化数组的情况下将32位浮点数按位转换为整值?

如何按预期聚合SON数据?

当在select中 Select 选项时,我必须禁用不匹配的 Select

如何在angular中从JSON值添加动态路由保护?

如何禁用附加图标点击的v—自动完成事件

在react JS中映射数组对象的嵌套数据

实现JS代码更改CSS元素

我怎么才能得到Kotlin的密文?

本地库中的chartjs-4.4.2和chartjs-plugin-注解

基于props 类型的不同props ,根据来自接口的值扩展类型

在Reaction中的handleSubmit按钮内,useSelector值仍然为空

为什么当我更新数据库时,我的所有组件都重新呈现?

无法重定向到Next.js中的动态URL

ngOnChanges仅在第二次调用时才触发

如何使用抽屉屏幕及其子屏幕/组件的上下文?

在GraphQL解析器中修改上下文值

我无法在Api Reaction本机上发出GET请求

如何在Highlihte.js代码区旁边添加行号?

使用Perl Selify::Remote::Driver执行Java脚本时出错

输入数据覆盖JSON文件