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

发布于 12-29 02:00 字数 210 浏览 3 评论 0原文

我目前正在为一个项目搞乱 tumblr API。

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

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

我考虑使用类似 substr() 的东西,但我不能保证要提取的字符数。

有什么想法吗?

I'm currently messing with the tumblr API for a project.

The problem I seem to have is I have to be able to extract the username from the src url e.g.

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

I looked into using something like substr() but I can't guarantee the number of characters to extract.

Any ideas?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

幼儿园老大2025-01-05 02:00:42

使用正则表达式:

> 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

using the regular expression:

> 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'

in short:

'http://you.tumblr.com/api/read/json'.match(/^http:\/\/(\w+)\./)[1]

will evaluate to

'you'

to elaborate:

^            match start of string
http:\/\/    match http://
(\w+)        match group of word characters which appears 1 or more times
\.           match a dot
苏佲洛2025-01-05 02:00:42

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

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

Here's a quick and dirty way without using a regex.

var str = "http://mydomain.tumblr.com/api/read/json";
var domainpart = str.substr(7, str.indexOf(".") - 7);
document.write(domainpart);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文