jQuery 从元素中删除特定文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8628324/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:47:50  来源:igfitidea点击:

jQuery Removing specific text from an element

jquery

提问by henryaaron

I want to remove the text "By:" from an element in my website. I want the rest of the text to remain there. How can I achieve that with jQuery? Thank you.

我想从我网站的元素中删除文本“By:”。我希望文本的其余部分保留在那里。我怎样才能用 jQuery 实现这一点?谢谢你。

The HTML

HTML

<div id="text">By: Anonymous From Minnesota</div>

I want it to just be:

我希望它只是:

<div id="text">Anonymous From Minnesota</div>

回答by Andrew Odri

If you wanted to find every element with "By:" in it and remove it, you could try this:

如果你想找到每个带有“By:”的元素并将其删除,你可以试试这个:

$(':contains("By:")').each(function(){
    $(this).html($(this).html().split("By:").join(""));
});

This removes any occurrence of "By:" in any element. If you want to target specfic type of elements, simply change $(':contains("By:")')to include whatever selector suits you.

这将删除任何元素中出现的任何“By:”。如果您想定位特定类型的元素,只需更改$(':contains("By:")')为包含适合您的任何选择器。

回答by Zoltan Toth

a more global solution using regular expressions. This will replace By:even if your string structure will change.

使用正则表达式的更全局的解决方案。By:即使您的字符串结构会改变,这也会替换。

var str = $('div').text().replace(/By:/g, '');
$('div').text(str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="text">By: Anonymous From Minnesota</div>

回答by themerlinproject

var str = $("#text").text();
$("#text").text(str.substring(3));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="text">By: Anonymous From Minnesota</div>

Using javascript's substringand give your div an ID to access it easily:

使用 javascriptsubstring并为您的 div 提供一个 ID 以便轻松访问它:

html:

html:

<div id="text">By: Anonymous From Minnesota</div>

jquery:

查询:

var str = $("#text").text();
$("#text").text(str.substring(3));

You could do it in one line too:

你也可以在一行中完成:

$("#text").text($("#text").text().substring(3));

回答by dku.rajkumar

give an unique id to div, t:

给 div 一个唯一的 id,t:

$('#div_id').html($('#div_id').html().substring(3));

fiddle : http://jsfiddle.net/ChUB4/

小提琴:http: //jsfiddle.net/ChUB4/