用jQuery隐藏文本中的字符?

我想将一些名为“Name:”的文字更改为“Name”。 换句话说,我只想隐藏’:’。

jQuery可以在div中选择一个字符或单词吗? 如果是这样,很容易隐藏’:’字符,或者如果需要将文本替换为相同的单词但没有该字符。

谢谢

如果你想使用JQuery那么,

$('#idOfTheTextDIV').html($('#idOfTheTextDIV').html().replace("texttoHide","")); 

javaScript replace()方法

示例代码:

  

你可以使用JavaScript的replace()

你可以使用javascript函数替换。

 var str = 'Name:'; str = str.replace(/:/g,''); 

这将基本上取代’:’char。

我认为最初的问题是jQuery是否可以根据节点的内容进行选择,而不是它是否可以进行替换。 答案是肯定的; 你可以按内容选择:

 $("div:contains('Name:')"); 

然后,您可以在该节点上执行简单的字符串替换,假设您不会在页面上还有其他实例,这些实例也具有“Name:”,您不想删除冒号:

 var $nameDiv = $("div:contains('Name:')") $nameDiv.html($nameDiv.html().replace(/:/g,""); // Copied from others. I didn't check this 

我不确定:contains()选择器有多贵 – 听起来很贵。 因此,将关键元素包装在带有ID的div中可能更好。

尝试下面的代码它工作正常。

 function removeSelectedText () { if (window.getSelection || document.getSelection) { var oSelection = (window.getSelection ? window : document).getSelection(); $('#text').text( $('#text').text().substr(0, oSelection.anchorOffset).replace( $('#text').text().substr(oSelection.focusOffset),'')); } else { document.selection.clear(); } } $('#remove').click(function() { removeSelectedText(); }); 
 $('#gridscroll').html($('#gridscroll').html().replace("'","")); 

‘hi’>> hi’

 $('#gridscroll').html($('#gridscroll').html().replace(/\'/g, "")); 

‘嗨’>>嗨