如何在特定字符后面添加空格,除非字符位于行的开头/结尾

时间:2016-01-19 05:02:57

标签: javascript jquery regex

我有一个改变所有这些模式的正则表达式:

anything1 * anything2* anything3
anything1* anything2 * anything3
anything1 * anything2 * anything3
anything1*anything2 *anything3
anything1 * anything2 *anything3
anything1*anything2*anything3

对于这种模式:

anything1 *anything2* anything3

这是我的正则表达式:

.replace(/\s*(\*+)\s*(.*?)\s*(\*+)\s*/g,' $1$2$3 ')
                                         ^      ^
                                           space

Demo

现在我想要如果星号在行的开头,那么第一个空格就会删除。像这样:

*anything1* anything2 anything3

如你所见,第一颗星(最左边)背后没有空间

此外,如果字符串以星号结尾,则最后一个空格将被删除。像这样:

anything1 anything2 *anything3*
//                             ^ there isn't any space there

我该怎么做?

注意:也许**代替*。这样的事情:anything **anything** anything

摘要:我试图删除此空间:

enter image description here

//                                              ^ this

1 个答案:

答案 0 :(得分:0)

如果您对两个单独的正则表达式(更容易阅读IMO)感到满意:

.replace(/^\s+\*/g, '*')
.replace(/\*\s+$/g, '*')