如何根据第 3 个字符子字符串,例如:我有字符串“aaa://Google/gmail”,我想获得一个新字符串,直到第 3 个“/”,新字符串 =“aaa://Google /"
问问题
133 次
3 回答
2
这样的事情应该做
var str = "aaa://Google/gmail",
matches = str.split('/');
str = matches.slice(0, 3).join('/') + ( matches.length > 3 ? '/' : '' )
如果你不关心斜杠,它更简单:
"aaa://Google/gmail".split('/').slice(0,3).join('/')
于 2012-10-24T09:44:35.357 回答
1
我会尝试一个正则表达式:
var s = "aaa://Google/gmail";
var regex = /.*?\/.*?\/.*?\// // or more sophisticated: /(?:.*?\/){3}/
s.match(regex);
另外,这看起来像你试图得到document.location.host
(也许document.location.protocol
)?
于 2012-10-24T09:53:24.097 回答
0
您还可以使用匹配:
var s = 'http://www.google.com/whatever';
var match = s.match(/^[^\/]*\/[^\/]*\/[^\/]*\//);
alert(match && match[0]); // http://www.google.com/
于 2012-10-24T09:51:30.377 回答