简体   繁体   English

使用Javascript获取字符串的一部分

[英]Get portion of a string using Javascript

I have a string (from the pathname in the url) and I am trying to pull out part of it, but I'm having trouble. 我有一个字符串(来自url中的路径名),我想取出其中的一部分,但是遇到了麻烦。

This is what I have so far: 这是我到目前为止的内容:

^(/svc_2/pub/(.*?).php)

The string is: 字符串是:

/svc_2/pub/stats/dashboard.php?ajax=1

How can I get a regex that returns /pub/stats/dashboard only? 如何获得仅返回/pub/stats/dashboard的正则表达式?

For this, using a regex is too much, but here is: 为此,使用正则表达式太多了,但这是:

var string = "/svc_2/pub/stats/dashboard.php?ajax=1";
console.log(string.replace(/.*(\/pub.*)\.php.*$/,"$1"));

But you can do it, without a regex, like this 但是,您可以在没有正则表达式的情况下做到这一点

console.log(string.substr(6,string.indexOf(".php")-6));

In both cases, the console.log will give you /pub/stats/dashboard 在这两种情况下,console.log都会为您提供/pub/stats/dashboard

If it's always that format (I'm assuming the /svc_2/ is always there) this should do it. 如果总是这种格式(我假设/ svc_2 /总是存在),则应该这样做。

var s = "/svc_2/pub/stats/dashboard.php?ajax=1";
var match = s.match(/\/svc_2(.+)\./)[1];

But not if anything comes before that. 但是在那之前没有什么。

This is not very flexible, but should work in this specific case. 这不是很灵活,但是应该在这种特定情况下起作用。

var basedir = '/svc_2/', str = '/svc_2/pub/stats/dashboard.php?ajax=1';
str = str.substring(basedir.length, str.indexOf('.'));
alert(str);

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

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