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.
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
看起来这也可以工作(尽管它确实返回了一个额外的空白字符串):
"one/two/three/four".split(/\/(.+)?/)
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>
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:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.