简体   繁体   English

在标签jquery中查找并替换文本

[英]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? <label id="labelId" class="control-label col-lg-4">Some text ()</label> ,如何在文本框中间插入文本并清除后?

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. 您必须使用text()获取文本,然后使用replace()替换文本,然后将替换的文本设置回标签。

jQuery solution : jQuery解决方案:

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

Pure js solution : 纯js解决方案:

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> 

You can also use .text(function) 您也可以使用.text(function)

A function returning the text content to set. 该函数返回要设置的文本内容。 Receives the index position of the element in the set and the old text value as arguments. 接收元素在集合中的索引位置和旧文本值作为参数。

 $('#labelId').text(function(index, text) { return 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> 

Try like this 这样尝试

 $(document).ready(function(){ $("#labelId").text($("#labelId").text().replace("()","(test)")); }) 
 <label id="labelId" class="control-label col-lg-4">Some text ()</label> <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM