javascript - 如何在字符串的第一个字母之前添加空格?
问题描述
我正在尝试使用正则表达式在字符串中的第一个字母之前添加空格。例如,如果我有一个字符串“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
谢谢
解决方案
在 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.
推荐阅读
- shell - 修复 zsh Shell 下的提示
- reactjs - 除非使用超时,否则 React setstate 在 IE 中不起作用
- sql - sql to dax - 连接2个多行表
- javascript - 通过 mshtml 将消息发布到外部 Javascript
- python - 尽管 socket.setdefaulttimeout() 操作超时
- html - 动态居中字段集中的 Div/文本
- docker - 错误:无法在 kubectl set image 中找到容器
- reactjs - SVG 单位制与预期不同
- typescript - 在下面的例子中,为什么 `fleet: vehicle3` 不抛出错误?
- angular - Angular 6:无法从第二个对话框发送 HTTP POST 请求