1

A label tag in my page looks like

<label>helloworld</label>

I want to append some arbitrary text to "helloworld" such that it becomes

<label>helloworld arbitrarytext</label>

This cannot be hardcoded as in many other posts suggest since that arbitrarytext always changes depending on my jquery. One way I am thinking is to remove the text and append string variable to the existing text and put it back, but it still feels not elegant and inefficient. Do anyone know any feature of jquery or javascript that can do this easily? Thanks!

3
  • Not elegant? Inefficient? What's easier than string concatenation and calling a method on an object? Commented Oct 13, 2015 at 0:44
  • I am looking for something that looks like <label>helloworld $arbitrarytext</label> Commented Oct 13, 2015 at 2:49
  • Well, JavaScript doesn't interpolate strings like a number of other scripting languages, so unfortunately, what you want to do is impossible. There's a sprintf() library, but that's seriously overkill for this task. Commented Oct 13, 2015 at 3:00

1 Answer 1

2

if you want replace one label text you can use

arbitrarytext= "arbitrarytext";
$("label").text($("label").text().replace("helloworld", "helloworld " + arbitrarytext));

for changing all lable text you can use:

arbitrarytext= "arbitrarytext";

$( "label:contains('helloworld')" ).each(function(index, element){
   $(element).text($(element).text().replace("helloworld", "helloworld " + arbitrarytext ));
})
Sign up to request clarification or add additional context in comments.

1 Comment

I thought I mentioned that arbitrarytext is an arbitrary text... It's a variable that will change all the time.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.