2

Using the following code:

<div class="whatever" addthis:title="Hi, your name is [firstName]"></div>

If I have a JS variable like this

var name = John

How would I replace the "[firstName]" with my JS variable in the first code snippet using jQuery?

It's ok if I need to set the attribute using jQuery to begin with like:

$('.whatever').attr( 'addthis:title', 'Hi, your name is [firstName].' );

2 Answers 2

4

Simply run replace on your string...:

var name = 'John';
$('.whatever').attr('addthis:title', function(i, attr){
    return attr.replace('[firstName]', name);
});

P.S. Are you sure you want an attribute addthis:title, not simply title? That's invalid HTML! If you want to create your own attributes, prefix them with data-:

<div class="whatever" data-addthis-title="Hi, your name is [firstName]"></div>
Sign up to request clarification or add additional context in comments.

1 Comment

Work perfectly. Regarding the invalid attribute, it's being used by the "Add This" social plugin.
0

Did you try it? Your example code contains all the pieces you need.

var name = "John";
var element = $('.whatever');
var newAttrValue = element.attr('addthis:title').replace(/\[firstName\]/, name);
element.attr('addthis:title', newAttrValue);

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.