Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split string into paragraphs using first comma?

I have string: @address = "10 Madison Avenue, New York, NY - (212) 538-1884" What's the best way to split it like this?

<p>10 Madison Avenue,</p>
<p>New York, NY - (212) 538-1884</p>
like image 913
peresleguine Avatar asked Jul 06 '11 10:07

peresleguine


People also ask

How do you split a string after a comma?

To split a string with comma, use the split() method in Java. str. split("[,]", 0);

How do you split a string into paragraphs?

Try something like this: var paragraphs = fileText. Split(new[] {paragraphMarker, "\n\n", "\r\r", "\r\n\r\n"}, StringSplitOptions. RemoveEmptyEntries); . You can also consider using regexp like var paragraphs = Regex.

How do you split a string on first occurrence?

To split a JavaScript string only on the first occurrence of a character, call the slice() method on the string, passing it the index of the character + 1 as a parameter. The slice method will return the portion of the string after the first occurrence of the character.

How do you split a string by a space and a comma?

To split a string by space or comma, pass the following regular expression to the split() method - /[, ]+/ . The method will split the string on each occurrence of a space or comma and return an array containing the substrings.


3 Answers

String#split has a second argument, the maximum number of fields returned in the result array: http://ruby-doc.org/core/classes/String.html#M001165

@address.split(",", 2) will return an array with two strings, split at the first occurrence of ",".

the rest of it is simply building the string using interpolation or if you want to have it more generic, a combination of Array#map and #join for example

@address.split(",", 2).map {|split| "<p>#{split}</p>" }.join("\n")
like image 139
Pascal Avatar answered Oct 07 '22 23:10

Pascal


break_at = @address.index(",") + 1
result = "<p>#{@address[0, break_at]}</p><p>#{@address[break_at..-1].strip}</p>"
like image 42
Dogbert Avatar answered Oct 07 '22 21:10

Dogbert


rather:

break_at = @address.index(", ")
result = "<p>#{@address[0, break_at+1]}</p><p>#{@address[break_at+1..-1]}</p>"
like image 1
Yerlan Kussainov Avatar answered Oct 07 '22 21:10

Yerlan Kussainov