简体   繁体   English

解析JavaScript中的某些字符串

[英]Parse certain string in javascript

I have a string that looks like this: var string = "something/123/bah/234/id/835/param/2343"; 我有一个看起来像这样的字符串:var string =“ something / 123 / bah / 234 / id / 835 / param / 2343”;

I want to just target the "835" that I need from "id". 我只想从“ id”中定位所需的“ 835”。 Any quick ways to strip that out? 有什么快速的方法可以消除这种情况吗?

Split it; 拆分; take the sixth object: 取第六个对象:

var string = "something/123/bah/234/id/835/param/2343"
var id = string.split("/")[5]; // "id" is 835 now

Or, if you want to get your id if it is located right after id/ and the location of id/ can change: 或者,如果你想获得你的ID,如果它位于右后id/和位置id/可改变:

var string = "something/123/bah/234/id/835/param/2343".split("/");
var id = string[string.indexOf("id")+1]; // "id" is 835 now
if(id==string[0]){id="No ID found"} // ...that's just if id happens not to be in your string

如果您要提取的数字不一定是第六部分,但是您知道它在字符串id后面并且由数字组成,则可以使用正则表达式

var id_part = string.match(/id\/(\d+)/)[1]

如果网址将更改并且仅保留id但在其他位置,则可以使用regex:

var id = string.match(/id\/([^\/]+)/i)[1];

You could use a regex, and pull out the id from a capture group. 您可以使用正则表达式,然后从捕获组中提取ID。 This would grab the id no matter what the position. 无论处于什么位置,都可以获取ID。

var string = "something/123/bah/234/id/835/param/2343";
var regex = /\/id\/(\d+)\//g
var match = regex.exec(string)
alert(match[1]); // 835

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM