57

How would i do this?

I got this:

name = "^aH^ai"
string.gsub(name, "^a", "")

which should return "Hi", but it grabs the caret character as a pattern character

What would be a work around for this? (must be done in gsub)

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
Frank
  • 573
  • 1
  • 4
  • 4

1 Answers1

95

Try:

name = "^aH^ai"
name = name:gsub("%^a", "")

See also: http://lua-users.org/wiki/StringLibraryTutorial

Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315
Kknd
  • 3,033
  • 26
  • 29
  • The tutorial uses a slightly different syntax. Why is `gsub` written with a `:` instead of a `.` in this answer? – Anderson Green Jun 21 '17 at 20:31
  • 20
    @AndersonGreen: it can be called as a library function of the `string` library or as a method on a `string` object. The `:` is syntax sugar in Lua which effectively implies the object on which the method is called being passed as first parameter. – 0xC0000022L Aug 31 '17 at 12:04
  • What if we want to replace special characters with special character? like email = email:gsub("%+", "%2b"). Effectively we want to to URL Encode the + to %2b – Diceyus Mar 17 '22 at 21:21