我搜索了SO并找到了一些解决方案,但它们是针对不同的语言而我无法翻译它们。由于我对此知之甚少,我希望转向专家寻求帮助。这就是我的技能带给我的:
到目前为止我的代码:
var str = "Tell us about this interaction. Make sure you mention: (a) what the interaction was about (hangout, chit chat, discuss assignments, etc.) (b) what other things you and/or your friend was doing on the phone during this interaction (c) whether both of you were involved in this other activity and (d) any other information about this interaction you would like to share with us. Avoid using your friends full real name";
var pat = /\([a-zA-Z]\)/g;
var out = str.replace(pat, "<br>");
alert(out);
此代码仅将匹配替换为&#39;&lt; br&gt;&#39;,忘记空格,论坛将翻译新的一行。
我想要获得的输出是:
&#34;告诉我们这种互动。请务必提及:&lt; br&gt;(a)交互的内容(环聊,聊天,讨论作业等)&lt; br&gt;(b)在此次互动期间,您和/或您的朋友在手机上正在做的其他事情&lt; br>(c)你们两个是否参与了这项其他活动并且&lt; br&gt;(d)您希望与我们分享的有关此互动的任何其他信息。避免使用你的朋友的真实姓名&#34;
感谢您的帮助,
查尔斯
答案 0 :(得分:2)
魔法$&
是您正在寻找的东西:)
var str = "Tell us about this interaction. Make sure you mention: (a) what the interaction was about (hangout, chit chat, discuss assignments, etc.) (b) what other things you and/or your friend was doing on the phone during this interaction (c) whether both of you were involved in this other activity and (d) any other information about this interaction you would like to share with us. Avoid using your friends full real name";
var pat = /\([a-zA-Z]\)/g;
var out = str.replace(pat, "<br>$&");
document.write(out);
答案 1 :(得分:0)
未执行匹配。您可以使用$ 1使用回调函数或模板。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_function_as_a_parameter
var str = "Tell us about this interaction. Make sure you mention: (a) what the interaction was about (hangout, chit chat, discuss assignments, etc.) (b) what other things you and/or your friend was doing on the phone during this interaction (c) whether both of you were involved in this other activity and (d) any other information about this interaction you would like to share with us. Avoid using your friends full real name";
var pat = /\([a-zA-Z]\)/g; // no match, use replace function.
var out = str.replace(pat, (t1) => `<br>${t1}`);
console.log(out);
var pat2 = /(\([a-zA-Z]\))/g; // match the group
var out2 = str.replace(pat2, '<br>$1');
console.log(out2)