我想用%20
的例子:
src="//myurl.com/example string.mp3"
src="//myurl.com/example%20string.mp3"
我正在寻找一个单个 RegEx选择器来做到这一点!我将使用Wordpress Search-Regex插件,如果你感兴趣的话。
出于使用正则表达式的乐趣,您可以替换:
src's*='s*"[^" ]*'K'h|(?!^)'G[^" ]*'K'h
使用%20
(将"
替换为'
以检查单引号字符串)
说明
这个想法是匹配src="...
模式的开始,直到我们找到一个空格或引号。这样,如果'G
锚点("end of last match")匹配,我们知道我们在相关的"..."
字符串中,我们可以愉快地匹配所有空格,直到关闭"
src's*='s*" # match the opening 'src="'
[^" ]* # match everything until a double quote or a space
'K # drop out what we matched so far
'h # match the whitespace (''h' is a horizontal whitespace)
|
(?!^)'G # match at the end of the last match (not beginning of string)
[^" ]*'K # match and drop until a double quote or a space
'h # match the whitespace
为了简单起见,该模式不处理转义引号。如果您需要这样做,您可以将[^" ]*
部分替换为(?:'''H|[^" '']++)*+
(参见这里的演示)
在一个模式中检查单引号和双引号字符串是不可行的(据我所知),如果你可以在"..."
字符串中有'
,反之亦然(如果你知道这不是一个问题,你可以使用src's*='s*['"][^'" ]*'K'h|(?!^)'G[^'" ]*'K'h
,参见这里的演示)。
假设我们有一个字符串
var src = "//my url.com/example string .mp3"
查找上述字符串中所有空格的正则表达式将为/'s/g
你可以用
替换javascript中的所有空格src = src.replace(/'s/g, '%20')