首页 > 解决方案 > 如何在字符串的第一个字母之前添加空格?

问题描述

我正在尝试使用正则表达式在字符串中的第一个字母之前添加空格。例如,如果我有一个字符串“0.5g”,我希望字符串变成“0.5 g”。

我试图运行一个正则表达式查询,在数字后添加一个空格,但是当它之间有一个小数点时,这会给我带来问题。

我目前的正则表达式是

'135mg'.replace(/(\d)([^\d\s%])/g, '$1 $2'); // Returns 135 mg as expected
'0.5g'.replace(/(\d)([^\d\s%])/g, '$1 $2'); // Returns 0. 5 g which is wrong as there is a whitespace before 5

谢谢

标签: javascriptregex

解决方案


在 JavaScript 中字符串的第一个字母之前添加一个空格是可能的

console.log( '135mg'.replace(/[a-zA-Z]/, ' $&') );
console.log( '135mg'.replace(/[a-z]/i, ' $&') );
console.log( '135mg'.replace(/([a-z])/i, ' $1') );

See the regex demo.

Note:

  • The regexps have no g flag, so only the first occurrence will get replaced
  • $& in the replacement pattern refers to the whole match, you actually do not need to wrap the whole pattern with a capturing group and use $1, but a lot of people still prefer this variation due to the fact $& is not well-known.

推荐阅读