How could you insert N number of commas into this string, before a space but not after a period or another comma? Using ruby or javascript.
Asked
Active
Viewed 968 times
2 Answers
5
One option:
>>> var str = "Lorem ipsum dolor sit amet consectetur adipiscing elit. Praesent mauris neque adipiscing nec malesuada id fermentum at eros. Curabitur eu neque nunc, et porta risus.";
>>> str.replace(/([^,.]) /g, '$1, ');
"Lorem, ipsum, dolor, sit, amet, consectetur, adipiscing, elit. Praesent, mauris, neque, adipiscing, nec, malesuada, id, fermentum, at, eros. Curabitur, eu, neque, nunc, et, porta, risus."
Alternatively, you can go another way in order to mimick negative lookbehind:
>>> var str = "Lorem ipsum dolor sit amet consectetur adipiscing elit. Praesent mauris neque adipiscing nec malesuada id fermentum at eros. Curabitur eu neque nunc, et porta risus.";
>>> str.replace(/([,.])? /g, function($0, $1) { return $1 ? $0 : ', '; });
"Lorem, ipsum, dolor, sit, amet, consectetur, adipiscing, elit. Praesent, mauris, neque, adipiscing, nec, malesuada, id, fermentum, at, eros. Curabitur, eu, neque, nunc, et, porta, risus."
-
Could this be re-purposed to insert only 3 (for example) randomly throughout the string? – ahabman Jun 10 '11 at 13:33
-
@ahabman Well, I guess you could add a random element: `str.replace(/([,.])? /g, function($0, $1) { return $1 || Math.random() > .2 ? $0 : ', '; });` will only replace ~1/5 (`.2`) of the qualified whitespaces. You *could* keep track of a maximum number of whitespaces (e.g., 3) to replace if you wanted to. – jensgram Jun 14 '11 at 05:32