字符替换

时间:2013-05-08 10:47:11

标签: javascript jquery regex

我有以下字符串值。

var stringVal = [4|4.6]^Size{1}~[6];

我希望在^发生第[1|5]次之前替换所有内容{{1}}如何进行此操作?

提前致谢。

1 个答案:

答案 0 :(得分:5)

一个简单的正则表达式会:

var stringVal = '[4|4.6]^Size{1}~[6]';
stringVal.replace(/^.*?\^/, '[1|5]^');
#=> "[1|5]^Size{1}~[6]"

正则表达式解释:

 ^   start of string
 .   any character
 *?  repeat >= 0 times, but match as less characters as possible (non-greedy)
 \^  match '^' (a simple `^` matches the start of the string, so we need to escape it

另一种更快的方法,适用于这种情况:

'[1|5]' + stringVal.substr(stringVal.indexOf('^'))