通过JavaScript提取字符串的特定部分
我目前正在处理一个项目的TumblrAPI 我的问题似乎是我必须能够从src url中提取用户名通过JavaScript提取字符串的特定部分,javascript,api,tumblr,Javascript,Api,Tumblr,我目前正在处理一个项目的TumblrAPI 我的问题似乎是我必须能够从src url中提取用户名 http://(you).tumblr.com/api/read/json 我考虑过使用类似substr()的东西,但我不能保证要提取的字符数 有什么想法吗 使用正则表达式: > var s = 'http://you.tumblr.com/api/read/json'; > var re = /^http:\/\/(\w+)\./; > s.match(re); [ 'http
http://(you).tumblr.com/api/read/json
我考虑过使用类似substr()
的东西,但我不能保证要提取的字符数
有什么想法吗 使用正则表达式:
> var s = 'http://you.tumblr.com/api/read/json';
> var re = /^http:\/\/(\w+)\./;
> s.match(re);
[ 'http://you.',
'you',
index: 0,
input: 'http://you.tumblr.com/api/read/json' ]
> s.match(re)[1]
'you'
简言之:
'http://you.tumblr.com/api/read/json'.match(/^http:\/\/(\w+)\./)[1]
将评估为
'you'
详细说明:
^ match start of string
http:\/\/ match http://
(\w+) match group of word characters which appears 1 or more times
\. match a dot
这里有一个不使用正则表达式的快捷方法
var str = "http://mydomain.tumblr.com/api/read/json";
var domainpart = str.substr(7, str.indexOf(".") - 7);
document.write(domainpart);
您可以使用常规表达式或
split('.')
与substr()