通过JavaScript提取字符串的特定部分

时间:2012-01-26 16:29:33

标签: javascript api tumblr

我目前正在搞乱项目的tumblr API。

我似乎遇到的问题是我必须能够从src网址中提取用户名,例如

http://(you).tumblr.com/api/read/json

我研究过像substr()之类的东西,但我无法保证要提取的字符数。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

使用正则表达式:

> 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

答案 1 :(得分:0)

这是一种快速而肮脏的方式,而不使用正则表达式。

var str = "http://mydomain.tumblr.com/api/read/json";
var domainpart = str.substr(7, str.indexOf(".") - 7);
document.write(domainpart);