I want to update the document title with jquery if something on the page updates. this is how it goes:
page loads: “regular page title”
some javascript activity, update page title to: “(1) regular page title”
some other unrelated activity, update page title to: “(2) regular page title”
some other other unrelated activity, update page title to: “(3) regular page title”
How can I do this using jquery, regular expressions. so that if no prior activity we just prepend (1) to regular page title (as per step 1 above).
any additional activity (such as step 2 and 3 above) reads that value (#) from page title and adds 1 to it.
I think LuckyB essentially wants to put a counter in the page title, and every time certain JS is run he wants to increment the counter by 1.
You could do it something like this:
function incrementTitle(){
var re = /(?:\\()*(\\d+)*(?:\\))*(.+)/;
var segments = document.title.match(re);
if (typeof segments[1] === "undefined"){
document.title = '(1) ' + segments[2];
} else {
var orginalValue = parseInt(segments[1],10);
var counter = '(' + (orginalValue + 1) + ')';
document.title = counter + ' ' + segments[2];
}
};
It seems to work OK, although I’m sure it could be more elegantly done. You could also just keep a counter in JS and avoid the regex nonsense altogether.
There’s probably a better way to achieve the same result - it’s usually more luck than judgement when it comes to regex!
(?:\\()*
This section looks for a left parenthesis, if it exists… the ?: at the beginning means that it’s a non-capturing match, so it won’t appear in the output.
(\\d+)*
\\d any digit, + one or more times, * zero or more times (making the group optional).
(?:\\))*
Another non-capturing group for the right parenthesis, if present;
(.+)
Captures any character except for the newline, this just grabs the rest of the title.
I used the MDN regex reference to help figure out how to create the pattern.
Yeah that’s a good point. In fact, if we’re going to make that assumption then we could reduce the code even further:
var originalTitle = document.title,
counter = 1;
function incrementTitle(){
document.title = '(' + counter++ + ') ' + originalTitle;
};
So we’ve done away with the regex altogether now. The only further thing I might want to do is hide the variables from the outside world… we keep the global scope a bit cleaner, and prevent accidental overwriting: