I would like to insert a <wbr>
tag every 5 characters.
Input: s = 'HelloWorld-Hello guys'
Expected outcome: Hello<wbr>World<wbr>-Hell<wbr>o guys
You can use the + operator to append a string to another. In this case, a + b + c , creates a new string.
A substring is a smaller part of a string, it's useful if you only want that specific part, like the beginning, middle, or end. How do you get a substring in Ruby? One way is to use a starting index & a number of characters, inside square brackets, separated by commas. The first number is the starting index.
index is a String class method in Ruby which is used to returns the index of the first occurrence of the given substring or pattern (regexp) in the given string. It specifies the position in the string to begin the search if the second parameter is present. It will return nil if not found.
chars is a String class method in Ruby which is used to return an array of characters in str. Syntax: str.chars. Parameters: Here, str is the given string. Returns: An array of the characters.
s = 'HelloWorld-Hello guys'
s.scan(/.{5}|.+/).join("<wbr>")
Explanation:
Scan groups all matches of the regexp into an array. The .{5}
matches any 5 characters. If there are characters left at the end of the string, they will be matched by the .+
. Join the array with your string
There are several options to do this. If you just want to insert a delimiter string you can use scan
followed by join
as follows:
s = '12345678901234567'
puts s.scan(/.{1,5}/).join(":")
# 12345:67890:12345:67
.{1,5}
matches between 1 and 5 of "any" character, but since it's greedy, it will take 5 if it can. The allowance for taking less is to accomodate the last match, where there may not be enough leftovers.
Another option is to use gsub
, which allows for more flexible substitutions:
puts s.gsub(/.{1,5}/, '<\0>')
# <12345><67890><12345><67>
\0
is a backreference to what group 0 matched, i.e. the whole match. So substituting with <\0>
effectively puts whatever the regex matched in literal brackets.
If whitespaces are not to be counted, then instead of .
, you want to match \s*\S
(i.e. a non whitespace, possibly preceded by whitespaces).
s = '123 4 567 890 1 2 3 456 7 '
puts s.gsub(/(\s*\S){1,5}/, '[\0]')
# [123 4 5][67 890][ 1 2 3 45][6 7]
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