Issues with string.gsub()

Hello devs!
I want this line of code to ouput <b>lol<b>

string.gsub("**lol**", "**", "<b>")

But instead it outputs <b>*<b>*<b>l<b>o<b>l<b>*<b>*<b>
I tried looking on google for a solution, but i couldn’t find much, the only somewhat useful info I found was that u can also use a table or function for the replacement parameter.

1 Like

* is a special magic character in string patterns
To fix this, just type a % to revert it.

Your code should look like:

print(string.gsub("**lol**", "%*%*", "<b>"))
-- outputs <b>lol<b>

This is what you would be looking for to be exact:

local text = "**lol** hiii"
local highlightedWord = string.match(text,"\*.*\*"):gsub("\*","")
local editedSample = string.gsub(text,"\*\*","")
local modifiedString = editedSample:gsub(highlightedWord, function()
	return `<b>{highlightedWord}</b>`



<b>lol</b> hiii

It’s complicated I know, I just took it from this post.

Basically it would properly replace the double asterisk with <b> and </b>

1 Like

Just wanted to add some additional details; glad my post helped though.

The * quantifier in string pattern will match 0 or more class. This meant that using just "**" as the pattern will make it match every blank character in the sample string, which is why you see it doing <b>char<b> repeatedly, the * needs to have a class (%d, %s, %w, etc). But since theres nothing before *, it uses a blank character as the class. So before you use any string matching functions (gmatch. match, gsub); escape your pattern accordingly

This will take some time to understand because I am not really an expert and string manipulation but thank you for letting me know! I really appreciate your help! Have a good day.

1 Like