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>
To split a string with comma, use the split() method in Java. str. split("[,]", 0);
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.
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.
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.
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")
break_at = @address.index(",") + 1
result = "<p>#{@address[0, break_at]}</p><p>#{@address[break_at..-1].strip}</p>"
rather:
break_at = @address.index(", ")
result = "<p>#{@address[0, break_at+1]}</p><p>#{@address[break_at+1..-1]}</p>"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With