Reputation: 5131
How would I go about removing the characters <
and >
from only a specific part of a string, say from the first 200 characters in that string? Those characters should remain untouched if they appeared after the 200 character mark.
Upvotes: 0
Views: 174
Reputation: 168259
Non-desctuctively:
text = "foo < bar > baz" * 20
"#{text[0...200].tr("<>", "")}#{text[200..-1]}"
Or, destructively:
text = "foo < bar > baz" * 20
text[0...200] = text[0...200].tr("<>", "")
Upvotes: 1
Reputation: 80095
str = "<aaa><bbbbb>ccccccccc<>"
str.prepend(str.slice!(0..10).delete('<>'))
Chops off a substring of n chars, cleans it from the unwanted chars and glues it back on.
Upvotes: 0
Reputation: 7437
Assuming what you want to do is replace the <
and >
characters with placeholders, you can do it like this:
if original_string.length >= 200
original_string = original_string[0..199].gsub(/</,"<").gsub(/>/,">") + original_string[200..-1]
else
original_string = original_string.gsub(/</,"<").gsub(/>/,">")
end
You could also use ""
as the substitution string.
Upvotes: 0