1

I have a string like this: "one/two/three/four" and I just want to return:

"one"
"two/three/four"

I'm not the greatest with regex expressions to split on, so was wondering if someone could help.

4 Answers 4

2

Just use String.prototype.split.

var components = "one/two/three/four".split("/");
console.log(components[0]);
console.log(components.slice(1).join("/"));

This will print:

one
two/three/four
Sign up to request clarification or add additional context in comments.

2 Comments

This doesn't work because the 1 argument to split limits the returned array to one element. Remove it and you should be fine.
@torazaburo You're right, I seriously have no idea why that 1 was there. I've removed it.
1

Looks like this will work as well (although it does return an extra blank string):

"one/two/three/four".split(/\/(.+)?/)

Comments

0

You can use indexOf()

<script>

function mySplit(s) {
    var pos = s.indexOf('/');
    if (pos != -1) return [s.substring(0,pos), s.substring(pos+1)];
    else return s;
}

console.log(mySplit('one/two/three/four'));
console.log(mySplit('test'));

</script>

Comments

0

Use a regexp as follows

var regex   = /(.*?)\/(.*)/;
var string  = "one/two/three/four";
var matches = string.match(regex);

console.log(matches[1], matches{2])

>> one two/three/four

In English, the regexp reads:

  • Match any string up to but not including a slash
  • Match everything after that

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.