Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regex - split string

Struggling with a regex requirement. I need to split a string into an array wherever it finds a forward slash. But not if the forward slash is preceded by an escape.

Eg, if I have this string:

hello/world

I would like it to be split into an array like so:

arrayName[0] = hello
arrayName[1] = world

And if I have this string:

hello/wo\/rld

I would like it to be split into an array like so:

arrayName[0] = hello
arrayName[1] = wo/rld

Any ideas?

like image 904
WastedSpace Avatar asked Jan 31 '11 16:01

WastedSpace


People also ask

Can you use regex to split a string?

You do not only have to use literal strings for splitting strings into an array with the split method. You can use regex as breakpoints that match more characters for splitting a string.

How do you split a string in Javascript?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

What is split regex?

split(String regex) method splits this string around matches of the given regular expression. This method works in the same way as invoking the method i.e split(String regex, int limit) with the given expression and a limit argument of zero. Therefore, trailing empty strings are not included in the resulting array.

How do you split a string with multiple separators?

Use the String. split() method to split a string with multiple separators, e.g. str. split(/[-_]+/) . The split method can be passed a regular expression containing multiple characters to split the string with multiple separators.


2 Answers

I wouldn't use split() for this job. It's much easier to match the path components themselves, rather than the delimiters. For example:

var subject = 'hello/wo\\/rld';
var regex = /(?:[^\/\\]+|\\.)+/g;
var matched = null;
while (matched = regex.exec(subject)) {
  print(matched[0]);
}

output:

hello
wo\/rld

test it at ideone.com

like image 123
Alan Moore Avatar answered Sep 23 '22 17:09

Alan Moore


The following is a little long-winded but will work, and avoids the problem with IE's broken split implementation by not using a regular expression.

function splitPath(str) {
    var rawParts = str.split("/"), parts = [];
    for (var i = 0, len = rawParts.length, part; i < len; ++i) {
        part = "";
        while (rawParts[i].slice(-1) == "\\") {
            part += rawParts[i++].slice(0, -1) + "/";
        }
        parts.push(part + rawParts[i]);
    }
    return parts;
}

var str = "hello/world\\/foo/bar";
alert( splitPath(str).join(",") );
like image 40
Tim Down Avatar answered Sep 25 '22 17:09

Tim Down