[英]Javascript regex split on first slash
我有一個像這樣的字符串:“一/二/三/四”,我只想返回:
"one"
"two/three/four"
我不是最擅長使用正則表達式的人,所以想知道是否有人可以提供幫助。
只需使用String.prototype.split
。
var components = "one/two/three/four".split("/");
console.log(components[0]);
console.log(components.slice(1).join("/"));
這將打印:
one
two/three/four
看起來這也可以工作(盡管它確實返回了一個額外的空白字符串):
"one/two/three/four".split(/\/(.+)?/)
您可以使用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>
使用正則表達式如下
var regex = /(.*?)\/(.*)/;
var string = "one/two/three/four";
var matches = string.match(regex);
console.log(matches[1], matches{2])
>> one two/three/four
用英語,正則表達式讀為:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.