Norman
Norman

Reputation: 6365

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

Upvotes: 2

Views: 334

Answers (2)

Vegeta
Vegeta

Reputation: 1317

Try this:

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

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

JSFiddle

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

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

Upvotes: 4

Related Questions