Search code examples
stringreplacelua

my code is right but Lua replace doesn't working (:gsub)


Hello I am trying to replace a specific text to "" and my code doesn't working. I just don't know why my code not working

b = 'Just testing.<script>window.location.replace("http://google.com");</script>'
print(b)
b = b:gsub('<script>window.location.replace("http://google.com");</script>', "")
print(b)

out 1: Just testing.window.location.replace("http://google.com");
out 2: Just testing.window.location.replace("http://google.com");

I tried b = string.gsub(b,'<script>window.location.replace("http://google.com");</script>',"") too but its doesn't worked either

I am working in FiveM


Solution

  • You need to escape ( and ), in a lua pattern they are recognized as special character. you can escape them using %

    b = 'Just testing.<script>window.location.replace("http://google.com");</script>'
    print(b)
    b = b:gsub('<script>window.location.replace%("http://google.com"%);</script>', "")
    print(b)
    

    For more infomration on lua patter you can look at these resources:

    Understanding Lua Patterns

    20.1 – Pattern-Matching Functions

    20.2 – Patterns