0

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.

3 Answers 3

6

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

str.sub!(word, '');
Sign up to request clarification or add additional context in comments.

Comments

4

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] = ""

Comments

3
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".)

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.