ErwinM
ErwinM

Reputation: 5131

Remove a specific character from a specific part of a string

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

Answers (3)

sawa
sawa

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

steenslag
steenslag

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

Austin Mullins
Austin Mullins

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(/</,"&lt;").gsub(/>/,"&gt;") + original_string[200..-1]
else
  original_string = original_string.gsub(/</,"&lt;").gsub(/>/,"&gt;")
end

You could also use "" as the substitution string.

Upvotes: 0

Related Questions