简体   繁体   English

如何在javascript中使用正则表达式获取基本URL

[英]how to get the base url using regex in javascript

My app is going to work in multiple env, in which i need to get the common value (base url for my app) to work across.. 我的应用程序将在多个环境中工作,我需要获得共同的价值(我的应用程序的基本网址)才能工作...

from my window location how to i get certain part from the start.. 从我的窗口位置如何从一开始就获得某些部分..

example : 例如:

    http://xxxxx.yyyy.xxxxx.com:14567/yx/someother/foldername/index.html

how can i get only: 我怎么才能得到:

http://xxxxx.yyyy.xxxxx.com:14567/yx/

my try : 我的尝试:

var base = \w([yx]/)

the base only select yx/ how to get the value in front of this? 基数只选择yx/如何获得前面的值?

this part.. 这部分..

thanks in advance.. 提前致谢..

If 'someother' is known to be the root of your site, then replace 如果已知“其他”是您网站的根,则替换

    \w([yx]/)

with

    (.*\/)someother\/

(note that the / characters are escaped here) which gives a first match of: (注意/字符在这里转义),它给出了第一个匹配:

   http://xxxxx.yyyy.xxxxx.com:14567/yx/

However, a regular expression may not be the best way of doing this; 但是,正则表达式可能不是这样做的最佳方式; see if there's any way you can pass the base URL in by another manner, for example from the code running behind the page. 看看是否有任何方式可以通过其他方式传递基本URL,例如从页面后面运行的代码。

If you don't mind disregarding the trailing slash, you can do it without a regex: 如果您不介意忽略尾部斜杠,则可以在没有正则表达式的情况下执行此操作:

var url = 'http://xxxxx.yyyy.xxxxx.com:14567/yx/someother/foldername/index.html';

url.split('/', 4).join('/');
//-> "http://xxxxx.yyyy.xxxxx.com:14567/yx"

If you want the trailing slash, it's easy to append with + '/' . 如果你想要尾部斜杠,很容易附加+ '/'

请尝试以下正则表达式:

http\:\/\/[\w\.]+\:\d+\/\w+\/

这个应该做得很好

http:\/\/[\w\.]+\:\d+\/\w+\/

Perhaps something like this? 也许是这样的?

Javascript 使用Javascript

function myBase(url, baseString) {
    if (url && baseString) {
        var array = url.split(new RegExp("\\b" + baseString + "\\b"));

        if (array.length === 2) {
            return array[0] + baseString + "/";
        }
    }

    return null;
}

var testUrl = "http://xxxxx.yyyy.xxxxx.com:14567/yx/someother/foldername/index.html",
    testBase = "yx";

console.log(myBase(testUrl, testBase))

; ;

Output 产量

http://xxxxx.yyyy.xxxxx.com:14567/yx/ 

On jsfiddle jsfiddle

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

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