繁体   English   中英

如何替换src属性中的所有空格?

[英]How to replace all spaces within src attribute?

我想用%20替换src属性内的所有空格

例:

src="//myurl.com/example string.mp3"

src="//myurl.com/example%20string.mp3"

我在寻找一个单一的正则表达式选择要做到这一点! 如果有兴趣,我将使用Wordpress Search-Regex插件。

为了获得使用正则表达式的乐趣,您可以替换:

src\s*=\s*"[^" ]*\K\h|(?!^)\G[^" ]*\K\h

%20 (代替"'检查单引号的字符串)。

说明(请参见此处的演示

这个想法是匹配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

为简单起见,该模式不处理转义引号。 如果需要,您可以将[^" ]*部分替换为(?:\\\\\\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')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM