1

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 = ???;

1 Answer 1

1

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

1 Comment

Awesome. Thanks for the idea.

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.