[英]How to replace all spaces within src attribute?
I would like to replace all spaces within the src attribute with %20
我想用
%20
替换src属性内的所有空格
Example: 例:
src="//myurl.com/example string.mp3"
to 至
src="//myurl.com/example%20string.mp3"
I'm looking for a single RegEx selector to do this! 我在寻找一个单一的正则表达式选择要做到这一点! I will be using the Wordpress Search-Regex plugin, should it be of interest.
如果有兴趣,我将使用Wordpress Search-Regex插件。
For the fun of doing it with a regex, you can replace: 为了获得使用正则表达式的乐趣,您可以替换:
src\s*=\s*"[^" ]*\K\h|(?!^)\G[^" ]*\K\h
With %20
(replace "
with '
to check single quoted strings). 与
%20
(代替"
与'
检查单引号的字符串)。
Explanation (see demo here ) 说明(请参见此处的演示 )
The idea is to match the beginning of the src="...
pattern, until we find a space or a quote. That way if the \\G
anchor ("end of last match") matches we know we're inside a relevant "..."
string and we can happily match all whitespaces, until a closing "
这个想法是匹配
src="...
模式的开头,直到找到一个空格或一个引号。这样,如果\\G
锚(“最后一个匹配的结尾”)匹配,我们就知道我们在一个相关的内部"..."
字符串,我们可以很高兴地匹配所有空格,直到结束"
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
To keep it simple the pattern doesn't handle escaped quotes. 为简单起见,该模式不处理转义引号。 If you need to do so you can replace the
[^" ]*
parts with (?:\\\\\\H|[^" \\\\]++)*+
(see demo here ) 如果需要,您可以将
[^" ]*
部分替换为(?:\\\\\\H|[^" \\\\]++)*+
(请参见此处的演示 )
Checking both single and double quoted strings in one pattern isn't doable this way (to my knowledge) if you can have a '
inside a "..."
string or vice versa (if you know that's not a worry, you can use src\\s*=\\s*['"][^'" ]*\\K\\h|(?!^)\\G[^'" ]*\\K\\h
, see demo here ). 如果您可以在一个
'
"..."
字符串中包含'
反之亦然,以一种方式检查单引号和双引号字符串都无法这样做(据我所知)(如果您不担心,可以使用src\\s*=\\s*['"][^'" ]*\\K\\h|(?!^)\\G[^'" ]*\\K\\h
,请参阅此处的演示 )。
Let us suppose that we have a string 让我们假设我们有一个字符串
var src = "//my url.com/example string .mp3"
the regex that will find all the spaces in the above string will be /\\s/g 将在上述字符串中找到所有空格的正则表达式为/ \\ s / g
you can replace all spaces in javascript using 您可以使用替换javascript中的所有空格
src = src.replace(/\s/g, '%20')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.