I need some help with RegEx, it may be a basic stuff but I cannot find a correct way how to do it. Please help!
我需要一些RegEx的帮助,它可能是一个基本的东西,但是我找不到正确的方法去做它。请帮助!
So, here's my question:
这是我的问题:
I have a list of URLs, that are invalid because of double slash, like this: http://website.com//wp-content/folder/file.jpg
, to fix it I need to remove all double slashes except the first one followed by colon (http://
), so fixed URL is this: http://website.com/wp-content/folder/file.jpg
.
我有一个URL列表,由于双斜杠而无效,比如:http://website.com//wp-content/folder/file.jpg,要修复它,除了第一个斜杠(http://),我需要删除所有的双斜杠,所以固定的URL是:http://website.com/wp-content/folder/file.jpg。
I need to do it with RegExp.
我需要用RegExp。
Variant 1
变体1
url.replace(/\/\//g,'/'); // => http:/website.com/wp-content/folder/file.jpg
url.replace(/ \ / \ / / g,' / ');/ / = > http:/website.com/wp-content/folder/file.jpg
will replace all double slashed (//
), including the first one, which is not correct.
将替换所有双割(//),包括第一个,这是不正确的。
example here: https://regex101.com/r/NhCVMz/2
例子:https://regex101.com/r/NhCVMz/2
2 个解决方案
#1
2
You may use
你可以用
url = url.replace(/(https?:\/\/)|(\/){2,}/g, "$1$2")
See the regex demo
看到regex演示
Note: a ^
anchor at the beginning of the pattern might be used if the strings are entire URLs.
注意:^锚的模式可以使用如果字符串是完整的url。
This pattern will match and capture http://
or https://
and will restore it in the resulting string with the $1
backreference and all other cases of 2 or more /
will be matched by (\/){2,}
and only 1 occurrence will be put back into the resulting string since the capturing group does not include the quantifier.
这种模式将匹配和捕获http://或https://,将恢复它在生成的字符串1美元backreference和所有其他情况下的2个或更多的/将匹配(\ /){ 2,},只有1发生将回产生的字符串自捕获组不包括量词。
#2
1
Find (^|[^:])/{2,}
Replace $1/
找到(^ |[^:])/ { 2,}替换1美元/
delimited: /(^|[^:])\/{2,}/
分隔:/(^ |[^:])\ / { 2,}
#1
2
You may use
你可以用
url = url.replace(/(https?:\/\/)|(\/){2,}/g, "$1$2")
See the regex demo
看到regex演示
Note: a ^
anchor at the beginning of the pattern might be used if the strings are entire URLs.
注意:^锚的模式可以使用如果字符串是完整的url。
This pattern will match and capture http://
or https://
and will restore it in the resulting string with the $1
backreference and all other cases of 2 or more /
will be matched by (\/){2,}
and only 1 occurrence will be put back into the resulting string since the capturing group does not include the quantifier.
这种模式将匹配和捕获http://或https://,将恢复它在生成的字符串1美元backreference和所有其他情况下的2个或更多的/将匹配(\ /){ 2,},只有1发生将回产生的字符串自捕获组不包括量词。
#2
1
Find (^|[^:])/{2,}
Replace $1/
找到(^ |[^:])/ { 2,}替换1美元/
delimited: /(^|[^:])\/{2,}/
分隔:/(^ |[^:])\ / { 2,}