当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Remove space before "]" using Regular Expressions

问题描述:

I'm stripping out parts of a string in JavaScript. Unfortunately at times it leaves me with a blank space before a closing bracket ] that I need.

For example, [shortcode type="default"] becomes [shortcode ], whereas I need it to be [shortcode]. Please note, there are multiple occurrences within the one string as the codes are built-up.

I need to strip out that blank space, if it occurs, before each occurrence of a ] combination. What is the regular expression for this?

网友答案:

You could use a positive lookahead.

str = str.replace(/\s+(?=])/g, "");

jsFiddle.

网友答案:

If there is a single space and a single occurrence, .replace(' ]', ']') is sufficient, but you say specifically that there will be more than one, so .replace(/ ]/g, ']') will do. If there can be more than one space before the closing brace, use:

.replace(/\s+]/g, ']')
网友答案:

If appearance of multiple spaces is possible, you should use \s+, like this:

str.replace(/\s+]/g, "]")

g at the end of /.../ does what you're asking for: replacing multiple occurrences in each line.

分享给朋友:
您可能感兴趣的文章:
随机阅读: