Kiran Dash
Kiran Dash

Reputation: 4956

Internationalization of strings with JavaScript Dynamic variable

There are two JS strings in my js file.

JS File Before localization:

var a = 'There are no stores in this area.';

Functions.php

wp_localize_script( 'store-locator', 'storelocatorjstext', array(
    'nostores'   => __( 'There are no stores in this area.', 'storelocator' )
) );

I use the above code to localize the script. And then in JS. I write the following

JS File After localization:

var a = storelocatorjstext.nostores;

This works fine. But what if I have a dynamic variable in my JS script? Like following

JS File Before localization:

var dynamic = 5;
var a = 'There are no stores in this area.';
var b = 'There are '+ dynamic +'stores in this area.';

Functions.php

wp_localize_script( 'store-locator', 'storelocatorjstext', array(
    'nostores'   => __( 'There are no stores in this area.', 'storelocator' ),
    'existingstores'   => __( 'There are 5 stores in this area.', 'storelocator' ) //I know this is wrong. How to add dynamic variable here like we do with PHP sprintf
) );

How to internationalize for the string with dynamic variable and how to use it in my JS file? Like we use sprintf and %s or %d in PHP.

JS File After localization:

var dynamic = 5;
var a = storelocatorjstext.nostores;
var b = ???;

Upvotes: 1

Views: 442

Answers (1)

Agustin Prosperi
Agustin Prosperi

Reputation: 61

Why not use javascript replace, something like:

php:

wp_localize_script( 'store-locator', 'storelocatorjstext', array(
    'nostores'   => __( 'There are no stores in this area.', 'storelocator' ),
    'existingstores'   => __( 'There are %s stores in this area.', 'storelocator' ) //I know this is wrong. How to add dynamic variable here like we do with PHP sprintf
) );

js:

var dynamic = 5;
var a = storelocatorjstext.nostores;
var b = storelocatorjstext.existingstores.replace("%s", dynamic);

Upvotes: 1

Related Questions