Vitaliy Vitaliy - 29 days ago 15
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

Answer

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.

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

  $('#labelId').text( label_text.replace("()", "(new)") );
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label id="labelId" class="control-label col-lg-4">Some text ()</label>