0

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.

3 Answers 3

1

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("<>", "")
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.