Ruby - Replace the First Occurrence of a Substring with Another String

Ruby - replace the first occurrence of a substring with another string

Use #sub:

a.sub('bar', "BAR")

How to replace substring with another substring (by index from..to)


str = 'show me the money'
first = 4
last = 11
replacement = '...'
str[first..last] = replacement
str
#=> 'show...money'

Replace words in a string - Ruby

You can try using this way :

sentence ["Robert"] = "Roger"

Then the sentence will become :

sentence = "My name is Roger" # Robert is replaced with Roger

Replace substring with another string rails

Try this, assuming the string is in a variable s:

s.gsub(/width:[^;]*;/, 'width: auto;')

Ruby match first occurrence of string for a gsub replacement

Use sub, not gsub. gsub is global, sub isn't.

How can I replace every instance of a pattern in ruby?

String.gsub should do the trick.

Quoting docs:

gsub(pattern, replacement) → new_str

Returns a copy of str with the all occurrences of pattern
substituted for the second argument. The pattern is typically a
Regexp; if given as a String, any regular expression metacharacters it
contains will be interpreted literally, e.g. \\d will match a
backlash followed by d, instead of a digit.

How do I remove the first occurence of a substring in string?

Use sub! to substitute what you are trying to find with ""(nothing), thereby deleting it:

phrase.sub!("foo", "")

The !(bang) at the end makes it permanent. sub is different then gsub in that sub just substitutes the first instance of the string that you are trying to find whereas gsub finds all instances.

Java replace only first occurrence of a substring in a string

Try the replaceFirst method. It uses a regular expression, but the literal sequence "ha" still works.

string.replaceFirst("ha", "gurp");


Related Topics



Leave a reply



Submit