Javascript对捕获的正则表达式执行算术运算 [英] Javascript perform arithmetic on captured regexp

查看:75
本文介绍了Javascript对捕获的正则表达式执行算术运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将标题从默认名称替换为"*number* new messages | default"

I want to replace my title from its default to "*number* new messages | default"

这是我拥有的代码,它从默认更改为1 new messages很好,但从未超过1.

Here is the code I have, it changes from default to 1 new messages fine, but it never goes above 1.

title = $('title').text();
regexp = /^(\d+)/

if (title.match(regexp))
  $('title').text().replace(regexp, (parseInt("$1")+1).toString())
else
  $('title').text('1 New Messages | Default')

推荐答案

您应该将函数用作

You should be using a function as the second argument to replace, you also need to set the new value:

var title = $('title').text();
$('title').text(title.replace(regexp, function(m) { return parseInt(m, 10) + 1) }));

和往常一样,当您调用 parseInt ,否则您迟早会感到不愉快.

And, as usual, don't forget the radix argument when you call parseInt or you will be unpleasantly surprised sooner or later.

这篇关于Javascript对捕获的正则表达式执行算术运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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