JS 获取 body 内 class 的数字字符串

2017-08-12 13:20:11 +08:00
 islujw

body 内有许多个 class,如:

<body class="default-template postid-123">

需要定位到前面是 "postid-" 的,并获取 123 这个字符串(长度不一定是 3 位)。

请问怎么做呢?将为第一个可用的答案发送感谢铜币。

2800 次点击
所在节点    JavaScript
9 条回复
soratadori
2017-08-12 13:30:47 +08:00
正则表达式

另外,铜币有啥用?
cojing
2017-08-12 13:31:50 +08:00
\d+
正则匹配数字就好
ferrum
2017-08-12 13:32:48 +08:00
```
var classnames = 'default-template postid-123'
var regId = /postid-([\d]+)/
var result = classnames.match(regId)
console.log(result[1])
```
老老实实问问题就行,别铜币来铜币去的。
geelaw
2017-08-12 13:39:21 +08:00
var result = / postid-([-_0-9a-zA-Z]+) /.exec(' ' + document.body.className + ' ');
result = result && result[1];

// 以上代码可以覆盖绝大多数情况了
islujw
2017-08-12 14:22:30 +08:00
@ferrum 谢谢,两者并不矛盾。铜币表示对帮助的尊重,虽然这个问题自己也试了一下,但我不希望被当作伸手党。
oott123
2017-08-12 17:51:58 +08:00
@geelaw 为啥前后都要拼空字符串呢?如果只是为了保证 string 类型,那么前面拼就可以了。
geelaw
2017-08-12 18:26:10 +08:00
@oott123 习惯,懒得思考
islujw
2017-08-12 19:19:02 +08:00
@ferrum class 名称不是固定的,有不定数量的 class,且一定包括 postid- 开头的。需要配合使用 document.body.className
flowfire
2017-08-28 11:49:55 +08:00
/(?: |^)postid-(\d+)(?: |$)/

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/382405

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX