Vitaliy Vitaliy - 3 months ago 41
Javascript Question

Find and replace text in label jquery

I've label for ex. :

<label id="labelId" class="control-label col-lg-4">Some text ()</label>
, how can i insert text in the middle of brakets and after clear it?

I've tried :

$('#labelId').replace("()", "(new)");

But that is not work for me


You've to get the text using text() replace it using replace() then set the replaced text back to the label.

jQuery solution :

var label_text = $('#labelId').text(); //Get the text
$('#labelId').text( label_text.replace("()", "(new)") ); //Replace and set the text back

Pure js solution :

var label_text = document.getElementById('labelId').innerText; //Get the text
document.getElementById('labelId').innerText = label_text.replace("()", "(new)"); //Replace and set the text back

Hope this helps.

  var label_text = $('#labelId').text();

  $('#labelId').text( label_text.replace("()", "(new)") );
<script src=""></script>
<label id="labelId" class="control-label col-lg-4">Some text ()</label>