Replace text in a string

Verified
Added by iNTERFACEWARE

Use string.gsub() to find and replace one or more instances of text within a string

Source Code
   -- replace "hello" with "Lua says hello"
   local s = "hello world"
   x = s:gsub( "hello", "Lua says hello")
   --> x="Lua says hello world"
      
   -- use a capture to duplicate (replace twice) each word in the string
   local s = "hello world"
   x = s:gsub( "(%w+)", "%1 %1")
   --> x="hello hello world world"
      
   -- use a capture to duplicate the first word in the string
   local s = "hello world"
   x = s:gsub( "(%w+)", "%1 %1", 1)
   --> x="hello hello world"
Description
Use string.gsub() to find and replace one or more instances of text within a string
Usage Details

Use string.gsub() to find and replace text within a string. The code demonstrates replacing a string “hello”, and also using a capture to duplicate each word in a string.

How to use the snippet:

  • Paste the code into your script
  • Inspect the annotations to see how it works