LJA
LJA

Reputation: 25

Replace text in string within an element after a specific character?

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!

Upvotes: 2

Views: 2276

Answers (3)

Jasper
Jasper

Reputation: 76003

//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]);
    }
});

Upvotes: 1

alex
alex

Reputation: 490453

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

Upvotes: 4

Johnny Craig
Johnny Craig

Reputation: 5000

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

Upvotes: 0

Related Questions