开发者

Javascript perform arithmetic on captured regexp

开发者 https://www.devze.com 2023-04-07 13:38 出处:网络
I want to replace my title from its default to \"*number* new messages | default\" Here is t开发者_如何学运维he code I have, it changes from default to 1 new messages fine, but it never goes above 1.

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

Here is t开发者_如何学运维he 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) }));

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


I came across this recently and the issue is to do with calling a function within the second argument of the replace function. The $1 is only valid if called directly in a string literal, not as a string argument to a function.

Another issue is that $('title').text().replace(regexp, (parseInt("$1")+1).toString()) will return a string. You need to pass the value you want to assign the text to as a function argument of the text() function like you have done in your else block.

Try this:

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

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

And a JSFiddle: http://jsfiddle.net/KFW4G/


replace returns a new string, so you have to use text again to set the text to the result.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号