用分组替换Javascript正则表达式

时间:2020-12-14 07:34:57

I've got an input which consists of a number passed as a string, such as "12345678". Sometimes, this might contain leading or trailing white space. The number needs to be stripped of any white space and prefixed with an identifier so that it looks like "P12345678" - Simple?

我有一个输入,其中包含一个以字符串形式传递的数字,例如“12345678”。有时,这可能包含前导或尾随空格。这个数字需要去除任何空白区域并以标识符为前缀,使其看起来像“P12345678” - 简单?

I thought of using the following regular expression but I can't seem to get the replacement to work correctly:

我想使用以下正则表达式,但我似乎无法使替换正常工作:

input = input.replace(/^\s*(\d+)\s*$/,/P\1/);

What am I doing wrong?

我究竟做错了什么?

1 个解决方案

#1


3  

Use this instead:

改为使用它:

input = input.replace(/^\s*(\d+)\s*$/, "P$1");

#1


3  

Use this instead:

改为使用它:

input = input.replace(/^\s*(\d+)\s*$/, "P$1");