簡體   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