在特定字符后替换元素中的字符串中的文本?
对JQuery来说很新
我试图在特定字符后出现的元素中删除字符串中的文本。
我明白这个:
Lorem ipsum dolor sit amet: consectetur adipisicing
我需要这个:
Lorem ipsum dolor sit amet
我是新手,非常感谢任何提供的帮助。 谢谢!
最简单的方法……
$('h3').text(function(i, text) { return text.split(':')[0]; });
jsFiddle 。
…但如果有子元素,这不会涵盖您。
这段代码将……
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()
等)使它更优雅。
//iterate through each `` tag $('h3').each(function (index, value) { //cache the current `
` element and get its text var $this = $(value), text = $this.text(); //check for the existence of a colon if (text.indexOf(':') > 0) { //split the text at the colon text = text.split(':'); //set the text of the current `
` element to the text before the first colon $this.text(text[0]); } });
你想使用javascript分割function
var x="abcd:efgh"; var mysplit=x.split(":"); var firsthalf=mysplit[0]; // = abcd var otherhalf=mysplit[1]; // = efgh