字符串将url替换为javascript中相同url的一部分

bflemi3

我有一个包含随机网址的字符串:

http://google.com/vocab/prefix#Billy

需要进行转换,以使直到(包括第一个#)的所有内容都被替换为最后一个/与第一个之间的值,#然后加上a :

结果将是:

prefix:Billy

更多示例:

http://some.url/a/path#elephant --> path:elephant
http://random.com/cool/black/beans/thing#Bob --> thing:bob

我知道如何捕获前缀部分/([^\/]+(?=#))/,但是由于无法弄清楚如何捕获需要替换的部分,我正在努力进行字符串替换。

myString.replace(/([^\/]+(?=#))/, '$1:')

我更愿意将string.replace与regex一起使用

智慧

使用replace方法时,您需要匹配所有要替换的模式,而不仅仅是需要保留的部分;这里有两个选择:

let s = 'http://google.com/vocab/prefix#Billy'

// using greedy regex
console.log(s.replace(/.*\/([^#]+)#/, '$1:'))

// adapted from OP's attempt
console.log(s.replace(/.*?([^\/]+?)#/, '$1:'))

注意.*part匹配要丢弃的子字符串,()捕获要保留的模式,然后重新格式化输出。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章