字符串操作,在数字前面插入一个字符串

时间:2014-01-31 07:44:04

标签: javascript regex

嗨,我有这个字符串。

"Remote Control 14.12, Foo Bar 41.2, Wooden Chair 83.13"

我想成功

"Remote Control - 14.12, Foo Bar - 41.2, Wooden Chair - 83.13"

尝试链接正则表达式,但我可以找到一种方法插入中间。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:4)

这是positive lookahead assertion的工作:匹配并替换空格,如果后跟数字:

result = subject.replace(/ (?=\d)/g, " - ");

<强>说明:

/ (?=\d)/g
^^^     ^^
|||     ||
|||     |Find all matches (not just the first one)
|||     End of regex
||Assert that the next character is a digit
|Match a space
Start of regex

如果你还想在一个数字之后插入一个短划线(但不是在字符串的末尾),你必须在一个单独的步骤中执行它,因为JavaScript可悲的缺乏对lookbehind的支持断言:

final_result = result.replace(/, /g, " - ");

答案 1 :(得分:1)

没有预见,你可以使用这个正则表达式:

var s = "Remote Control 14.12, Foo Bar 41.2, Wooden Chair 83.13";
var r = s.replace(/( \d)/g, " -$1");
//=> "Remote Control - 14.12, Foo Bar - 41.2, Wooden Chair - 83.13"

搜索:

1st Capturing group ( \d) - capture this string into `$1` where
  matches the character " " (space) literally
  \d match a digit [0-9]

替换为:

 " -$1" which is space followed by hyphen followed by $1 (back reference to string captured)