TravelWhere TravelWhere - 4 months ago 14
Javascript Question

Remove string after character in every line break

Hi I'm a newbie at javascript and I have some text that contains multiple lines.I want to remove strings after the character '(' in every line breaks and then replace all line breaks with commas. This is what I have so far

var text = "black gloves (?) 36622\nred eyes (?) 587624\nsolo (?) 1975043\nshort hair (?) 1628547"

var draft = text.replace(/(\r\n|\n|\r)/gm,",");
var final = draft.split('(')[0];
alert(final);


I can't seem to get my code to give me this result:

black gloves,red eyes,solo,short hair


but instead it just gives
black gloves

Answer

Try this:

var text = "black gloves (?) 36622\nred eyes (?) 587624\nsolo (?) 1975043\nshort hair (?) 1628547"

var draft = text.replace(/(\r\n|\n|\r)/gm," ");
var draft = draft.replace(/(\d)+/gm,",");
var draft = draft.replace(/\(\?\)/gm,"");
alert(draft);

OR

var text = "black gloves (?) 36622\nred eyes (?) 587624\nsolo (?) 1975043\nshort hair (?) 1628547"

var draft = text.replace(/\(\?\)[ \d\r\n]+/gm,",");
alert(draft);