tob88
tob88

Reputation: 2211

Remove single instance of inner characters from a string

I would like to remove a single occurrence of a word from a string:

str = "I would like to remove THIS word but not THIS word"

I only want to remove the first 'THIS', giving the result:

str = "I would like to remove  word but not THIS word"

I was thinking of something along the lines of index:

word = 'THIS'
word.length # => 4
str.index(word) # => 23

Is there any way to say, remove 4 characters after the 23rd character?

I see there are a lot of ways to remove the leading and trailing characters, but not sure about inner characters. Gsub would remove all instances of the word, which is not what I'm looking for.

Upvotes: 0

Views: 916

Answers (3)

Cary Swoveland
Cary Swoveland

Reputation: 110755

str = "I would like to remove THIS word but not THIS word"
str.sub!(/\bTHIS\b/,'')
  #=> "I would like to remove  word but not THIS word" 

str = "THISTLE sounds like WHISTLE. I want to remove THIS word"
str.sub!(/\bTHIS\b/,'')
  # => "THISTLE sounds like WHISTLE. I want to remove  word"

whereas

str.sub("THIS", '')
  #"TLE sounds like WHISTLE. I want to remove THIS word"

\b in the regex is a "word break". (Search on "anchors".)

Upvotes: 3

sawa
sawa

Reputation: 168259

To remove only the first occurrence of THIS, do:

str.sub!("THIS", "")

To remove four characters after the 23rd character (i.e., from the 24th character), do:

str[24, 4] = ""

Upvotes: 4

Ursus
Ursus

Reputation: 30071

You can use sub, it affects just the first matching occurrence.

str.sub!(word, '');

Upvotes: 6

Related Questions