2

This is something that has been bothering me for a while.

Assume I'm doing this on a line

var result = "Noble warm and pretty darm Caesar.".split(/(\warm)/);
// ["Noble ", "warm", " and pretty ", "darm", " Caesar."]

Would it be possible to extend the split method in order to manipulate regexp catches with a function like replace does on strings?

Pseudo-code:

var result = "Noble warm and pretty darm Caesar.".split(/(\warm)/, function (match) {
        return '<span style="color:red;">' + match + '</span>';
});
// ["Noble ", "<span style=\"color:red;\">warm</span>", " and pretty ", "<span style=\"color:red;\">darm</span>", " Caesar."]
5
  • 1
    Well, you can create your own function which then iterates over the array and makes the replacements as necessary. Commented Jan 12, 2013 at 16:32
  • There's really nothing in JavaScript that can be described as "extending a method". You can write new code that uses .split() and then does more work. Commented Jan 12, 2013 at 16:33
  • @Pointy: Poor choice of words, I meant 'extending' in a more lightweight sense. Commented Jan 12, 2013 at 16:34
  • Right, and as Mr. Kling says you can certainly write code to do something to the elements of the array returned by .split(). Be aware that browsers aren't necessarily consistent with what's returned from .split() when you call it with a regex. Commented Jan 12, 2013 at 16:35
  • @Pointy: Perhaps I should actually modify a JavaScript implementation of the .split() method and use String.prototype.splitNew? Commented Jan 12, 2013 at 16:38

1 Answer 1

1

You can define your own function in the prototype object property of the String object.

The following function is an example of what you could do :

String.prototype.splitReplace = function(pattern, fn)
{
    var array = this.split(pattern);
    for (var i = 0; i < array.length; i++)
    {
        if (i % 2 == 1)
        {
            array[i] = fn(array[i]);
        }
    }
    return array;
}

As stated above, this function is just a quick example, to show how you could add a function to the String prototype property. But you should use the smart and robust function declaration @User2121315 gave us in the comments

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

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.