[SalesForce] Removing special characters: Serverside Javascript + Ampscript

I'm currently learning Ampscript and SSJS for an email project. I'm trying to remove special characters to a specific object that is being called.
I've came across some things that I think that could help but isnt sure how to use them.

Creating a template for an exact target email. Thought I could use the string.replace as show below. What would be some other options if any?

string = string.replace(/[^a-zA-Z0-9]/g, '');

Current code section below : the @img automatically pull content with special characters that needs to be removed before being used in the email

If RowCount(@customTemplate) != 0 Then
    Set @costumTemplate = True
    Set @img = Lowercase(Replace(@first_artist, ' ','_'))
  ElseIf RowCount(@locationTemplate) != 0 Then
    Set @locationTemplate = True
    Set @img = Lowercase(Replace(@venue_name,' ','_'))
  EndIf

Best Answer

I'd advise against using SSJS in your emails, especially since there is a native AMPScript function for doing the same thing.

Here are a few regex examples from my blog:

%%[
var @s, @o, @p, @m

outputLine(concat("<h4>Strip leading zeroes from a string</h4>"))
set @s = "0000012345"
set @p = "^0*(\d+)$"
set @o = RegExMatch(@s, @p, 1)
outputLine(concat("input:  ",@s,"<br>"))
outputLine(concat('pattern: "',@p,'"<br>'))
outputLine(concat("output: ",@o,"<br>"))

outputLine(concat("<h4>Check for all digits, no match</h4>"))
set @s = "12345x"
set @p = "^\d*$"
set @o = RegExMatch(@s, @p , 0)
outputLine(concat("input: ",@s,"<br>"))
outputLine(concat('pattern: "',@p,'"<br>'))
outputLine(concat("output: ",@o,"<br>"))

outputLine(concat("<h4>Check for all digits, match</h4>"))
set @s = "12345"
set @p = "^\d*$"
set @o = RegExMatch(@s, @p , 0)
outputLine(concat("input: ",@s,"<br>"))
outputLine(concat('pattern: "',@p,'"<br>'))
outputLine(concat("output: ",@o,"<br>"))

outputLine(concat("<h4>Replace parenthetical text with space</h4>"))
set @s = "whee (whatever it is) whoop"
set @p = "\s\(.+\)\s"
set @m = RegExMatch(@s, @p, 0 , "IgnoreCase")
set @o = replace(@s,@m, " ")
outputLine(concat("input:  ",@s,"<br>"))
outputLine(concat('pattern: "',@p,'"<br>'))
outputLine(concat("match: ",@m,"<br>"))
outputLine(concat("replaced: ",@o,"<br>"))

]%%

Reference:

RegExMatch() Function

Related Topic