1

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?

1
  • text = text.replace(/\$seconds|\d+/, seconds); Commented Dec 13, 2016 at 11:27

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.