Reputation: 628
I've searched SO and found some solutions but they were for a different language and I wasn't able to translate them. Since I know very little about this I hope to turn to the experts for help. This is as far as my skills have taken me:
My code so far:
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);
This code only replaces the match with '< br >', forget the spaces, the forum will translate the new line.
The output I'm trying to get is this:
"Tell us about this interaction. Make sure you mention: < br >(a) what the interaction was about (hangout, chit chat, discuss assignments, etc.) < br >(b) what other things you and/or your friend was doing on the phone during this interaction < br >(c) whether both of you were involved in this other activity and < br >(d) any other information about this interaction you would like to share with us. Avoid using your friends full real name"
Thank you for any help,
Charles
Upvotes: 6
Views: 11881
Reputation: 18995
Magical $&
is the thing you're looking for :)
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);
Upvotes: 13
Reputation: 1393
The match isn't performed. You can use a callback function or templates using $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)
Upvotes: 2