简体   繁体   中英

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.

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("<>", "")

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM