1

When translating PHP-strings with variables, I use the following approach:

sprintf(__('Some text <b>%s</b>, more text.','my-plugin' ), $somestring);

When translating javascript strings, I use this approach:

wp_register_script( 'my_script', 'my_file.js' );
$translation_array = array(
     'original_string' => __( 'Original string', 'my-plugin' )
);
wp_localize_script( 'my_script', 'script_strings', $translation_array );
wp_enqueue_script( 'my_script' );

But how can I include javascript variables in the translated javascript strings, if I want to translate a string like the following?

var somevariable = 'somecontent';
console.log('This is my original string from ' + somevariable + ' some more text');

Thanks,

4
  • This is what you are looking for. However, it's not a WordPress question since you are going to do it on client's browser.
    – Johansson
    Sep 5, 2017 at 6:28
  • Thanks. What's the generally used approach for this? would you normally just split the string in 2 translations, or would you add a function that works like sprintf does in PHP like suggested in the other question? Sep 5, 2017 at 6:36
  • JS doesn't have a function like sprint, so you either have to create one for it or use a library ( in the provided link ), or you have to use find and replace or .format ( also included in the link ).
    – Johansson
    Sep 5, 2017 at 6:41
  • Yeah. I get that. I wast just wondering whether the best approach would be to use the approach from the link, or just simply add the needed strings as 2 translations.. 'This is my original string from ' & ' some more text' - then concat them with the variable. Sep 5, 2017 at 6:42

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy