如何使用 Javascript 在给定的句子中查找大写单词并在其之前添加一个字符?

How to find capitalized word and add a character before that in given sentence using Javascript?

所以我有这样一个字符串:

var response = "Connecting to server Connection has been successful We found result";

我想在找到第二个大写单词后在每个大写单词前插入一个','。

我正在这样做:

var response = "Connecting to server Connection has been successful We found result";
var pattern=/[A-Z]/g;
document.write(response.replace(pattern,','));

结果:

,onnecting to server ,onnection has been successful ,e found result

我想要的:

Connecting to server,Connection has been successful, We found result

试试这个:

var str = "Connecting to server Connection has been successful We found result";

str.replace(/.[A-Z]/g, ',$&'); 

结果:正在连接服务器,连接成功,找到结果

When a match is found, if you want to include the matched text in the replacement string, you can access it using $&.

replace 一个 space 后跟一个带逗号的大写字母加上该分组 (</code>).</p> <pre><code>var res2 = response.replace(/( [A-Z])/g, ',');

DEMO

您可以使用正则表达式和正则先行。

String#replace(/ (?=[A-Z])/g, ', ')

document.write('Connecting to server Connection has been successful We found result'.replace(/ (?=[A-Z])/g, ', '));