Javascript 字符替换
我有以下字符串值Javascript 字符替换,javascript,jquery,regex,Javascript,Jquery,Regex,我有以下字符串值 var stringVal = [4|4.6]^Size{1}~[6]; 我想用[1 | 5]替换第一次出现^之前的所有内容。我该如何做 提前谢谢 一个简单的正则表达式可以: var stringVal = '[4|4.6]^Size{1}~[6]'; stringVal.replace(/^.*?\^/, '[1|5]^'); #=> "[1|5]^Size{1}~[6]" 正则表达式解释: ^ start of string . any charact
var stringVal = [4|4.6]^Size{1}~[6];
我想用[1 | 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('^'))
一个简单的正则表达式可以:
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('^'))
@MohammadAdil,我想我应该在每个答案中都这样做,很多人都很感激@MohammadAdil,我想我应该在每个答案中都这样做,很多人都很感激