简体   繁体   中英

Adding removing leading and trailing spaces in this JavaScript RegEx

How do I add code to remove leading and trailing spaces to this regular expression?

I tried putting the \\s in several places, but end up with odd results.

The myString is just the way it is, and is sent from a PHP script with trailing spaces.

Original Code

var myString = "::This is string 1 ::This is string 2! ";

myString = myString.replace(/\::(.+?)(?![^::])/g,'<li>$1</li>');

alert(myString);

Tried

var myString = "::This is string 1 ::This is string 2! ";

myString = myString.replace(/\::(.+?)(?![^::\s])/g,'<li>$1</li>');

alert(myString);

The end result I'm trying to achieve is

<li>This is string 1</li> // No trailing spaces before or after the `This` and `1`
<li>This is String 2</li>

Fiddle

The point is that you match spaces with .+? , and (?![^::\\s]) only tells the regex engine to not match a character if it is followed by a whitespace or : .

Since you already are using lazy matching, you just need to use a greedy \\s* subpattern to match whitespaces after the .+? .

Use

::(.+?)\s*(?=::|$)

See demo

Explanation:

  • :: - match 2 : s
  • (.+?) - match and capture into Group 1 one or more characters other than a newline
  • \\s* - greedily match zero or more whitespaces
  • (?=::|$) - only if followed by :: or end of string.

And here is my attempt at unrolling the regex (looks a bit more efficient than the above):

::(\S*(?:(?=(\s+))\2(?!:|$)\S*)*)

See another demo

Try this:

var myString = "::This is string 1 ::This is string 2! ";

myString = myString.replace(/\s*\::\s*(.*?)\s*(?=(::|$))/g,'<li>$1</li>');

JSFiddle

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