在特定字符后替换元素中字符串中的文本? [英] Replace text in string within an element after a specific character?

查看:85
本文介绍了在特定字符后替换元素中字符串中的文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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).

这篇关于在特定字符后替换元素中字符串中的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆