简体   繁体   English

在此JavaScript RegEx中添加删除前导和尾随空格

[英]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. 我尝试将\\s放在几个地方,但结果却很奇怪。

The myString is just the way it is, and is sent from a PHP script with trailing spaces. myString就是这样,它是从with尾随空格的PHP脚本发送的。

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 : . (?![^::\\s])仅告诉正则表达式引擎在后跟空格或:不匹配该字符。

Since you already are using lazy matching, you just need to use a greedy \\s* subpattern to match whitespaces after the .+? 由于您已经在使用惰性匹配,因此只需要使用贪婪的\\s*子模式来匹配.+? 的空格.+? .

Use 采用

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

See demo 观看演示

Explanation: 说明:

  • :: - match 2 : s :: -匹配2 : s
  • (.+?) - match and capture into Group 1 one or more characters other than a newline (.+?) -匹配并捕获到第1组中的一个或多个字符(换行符除外)
  • \\s* - greedily match zero or more whitespaces \\s* -贪婪地匹配零个或多个空格
  • (?=::|$) - 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 的jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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