简体   繁体   中英

How to replace all spaces within src attribute?

I would like to replace all spaces within the src attribute with %20

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.

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).

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\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 )

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 ).

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

you can replace all spaces in javascript using

src = src.replace(/\s/g, '%20')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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