Reputation: 780
I've some problem with a string replace, in particular I've a php that return an array, each index of array contains a specific string of translation. So essentially, this array are saved inside: GlobalVariables.language['hello_world']
, that for example return Hello world
.
Now I've an array index that contains this translation string:
wait $seconds seconds before try again
I set the seconds inside an interval function that working as a countdown:
setInterval(function ()
{
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
text = text.replace('$seconds', seconds);
console.log(text);
$('.alert').text(text);
if (--timer < 0)
{
timer = 0; //Stoppo il timer
}
}, 1000);
this will return a string like this:
wait 20 seconds before try again
but only for the first time, 'cause later the $seconds part of the string is already replaced, I though to replace only digital number of text for second timing, but I can't do this 'cause before call setInterval I append the string to another that contains a digital number.
How can I solve this problem?
Upvotes: 1
Views: 69
Reputation: 133433
First time it works as $seconds
is found in the string. However next time(2nd iteration onward) since $seconds
not exists in the text
, thus its not replaced.
You should persist original with element and used it as template.
//Perists original text with element
var alertElem = $('.alert');
alertElem.data('text', text);
setInterval(function (){
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
alertElem.text(function(){
return alertElem.data('text').replace('$seconds', seconds)
});
if (--timer < 0)
{
timer = 0;
}
}, 1000);
Upvotes: 1
Reputation: 15164
dont replace the original variable but use a different one.
text
will then always contain $seconds
:-
setInterval(function() {
minutes = parseInt(timer / 60, 10);
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
var text2 = text.replace('$seconds', seconds);
console.log(text2);
$('.alert').text(text2);
if (--timer < 0) {
timer = 0; //Stoppo il timer
}
}, 1000);
Upvotes: 1