2

very new to JQuery

I'm trying to strip out text in a string within an element that that appears after a specific character.

I'm getting this:

<h3>Lorem ipsum dolor sit amet: consectetur adipisicing</h3>

And I need this:

<h3>Lorem ipsum dolor sit amet</h3>

I'm a newbie and would really appreciate any help offered. Thanks!

3 Answers 3

4

The easiest way...

$('h3').text(function(i, text) {
   return text.split(':')[0];
});

jsFiddle.

...but this won't cover you if there are child elements.

This code will...

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.

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

Sign up to request clarification or add additional context in comments.

Comments

1
//iterate through each `<h3>` tag
$('h3').each(function (index, value) {

    //cache the current `<h3>` 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 `<h3>` element to the text before the first colon
        $this.text(text[0]);
    }
});

Comments

0

you want to use the javascript split function

var x="abcd:efgh";

var mysplit=x.split(":");

var firsthalf=mysplit[0]; // = abcd
var otherhalf=mysplit[1];  // = efgh

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.