2

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

2

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

1

Try this:

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

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

JSFiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.