I want to replace my title from its default to "*number* new messages | default"
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')
3 Answers 3
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.
3 Comments
parseInt
optional is a bug in the JavaScript spec. You almost never want parseInt
to guess the radix so parseInt's interface is (IMHO) broken by design. Can't change it now though :)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/
Comments
replace
returns a new string, so you have to use text
again to set the text to the result.
match
overtest
in this implementation? Also, can you provide an example (or examples) of what$('title').text()
may have? (Finally, are you sure it's not#title
or.title
as the selector?)parseInt("1ドル")
? That will give youNaN