在特定字符后替换元素中字符串中的文本?
问题描述:
JQuery的新手
我正在尝试去除出现在特定字符之后的元素中字符串中的文本.
I'm trying to strip out text in a string within an element that that appears after a specific character.
我得到这个:
<h3>Lorem ipsum dolor sit amet: consectetur adipisicing</h3>
我需要这个:
<h3>Lorem ipsum dolor sit amet</h3>
我是新手,非常感谢您提供的任何帮助. 谢谢!
I'm a newbie and would really appreciate any help offered. Thanks!
答
最简单的方法...
$('h3').text(function(i, text) {
return text.split(':')[0];
});
jsFiddle .
...但是,如果有子元素,这不会覆盖您.
...but this won't cover you if there are child elements.
此代码将...
var searchText = function(parentNode, regex, callback) {
var childNodes = parentNode.childNodes,
node;
for (var i = 0, length = childNodes.length; i < length; i++) {
node = childNodes[i];
if (node.nodeType == 0) {
var tag = node.tagName.toLowerCase();
if (tag == 'script' || tag == 'style') {
continue;
}
searchText(node);
} else if (node.nodeType == 3) {
while (true) {
// Does this node have a match? If not, break and return.
if (!regex.test(node.data)) {
break;
}
node.data.replace(regex, function(match) {
var args = Array.prototype.slice.call(arguments),
offset = args[args.length - 2],
newTextNode = node.splitText(offset);
callback.apply(window, [node].concat(args));
newTextNode.data = newTextNode.data.substr(match.length);
node = newTextNode;
});
}
}
}
}
searchText($('h3')[0], /:.*$/, function(node) {
$(node).next().remove();
});
jsFiddle .
我从一些不使用jQuery库的代码中改编了这段代码.您可以使用jQuery使它更加优雅(例如children()
,each()
,makeArray()
等).
I adapted this code from some code that doesn't use the jQuery library. You could make it slightly more elegant with jQuery (such as children()
, each()
, makeArray()
, etc).