[英]JavaScript - Get only a part of the string after a particular expression
我有以下几点:
var string = 'https://sub.example.com/dir/ https://sub.example.com/dir/v2.5/'
var hostname = 'sub.example.com';
var hostname_match = hostname.replace(/\./g, '\\.');
string.replace(new RegExp('https\:\/\/'+hostname_match+'\/(.*)', 'g'), '/$1');
我想要得到以下内容:
/dir/ /dir/v2.5/
您可以只替换http:// + hostname
:
var string = 'https://sub.example.com/dir/ https://sub.example.com/dir/v2.5/' var hostname = 'sub.example.com'; let urls = string.split(' ') .map(u => u.replace('https://'+hostname, '')) console.log(urls) // if you want a space-separated string: console.log(urls.join(' '))
您可以使用
new RegExp('https://'+hostname_match+'/(\\S*)', 'g')
在此, .*
被\\S*
替换为零个或多个非空白字符。
参见JS演示:
var string = 'https://sub.example.com/dir/ https://sub.example.com/dir/v2.5/' var hostname = 'sub.example.com'; var hostname_match = hostname.replace(/\\./g, '\\\\.'); console.log( string.replace(new RegExp('https://'+hostname_match+'/(\\\\S*)', 'g'), '/$1') );
请注意,由于/
不是特殊的正则表达式元字符,因此您无需在构造函数表示法中转义正斜杠。 在任何正则表达式上下文中都不必转义冒号。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.