Search code examples
javascriptregexvelocity

Javascript Regex to replace any non-alphanumeric characters, including brackets


I have this regex /[\W_]+/g that I use to remove any non-alphanumeric characters. However it does not remove brackets.

What I need is for it to remove any kind of bracket/paranthesis so that a string like Hello (world) becomes helloworld.

A string like Hello(world) becomes helloworld, but it does not work if there is a space between them.

Is this possible?


Solution

  • You should be able to use this Java / JavaScript compliant regex according to RegexBuddy 4.x: ([\W\s_]+)

    And just replace anything it matches with '' or ""

    Following the documentation here, something like this:

    #set($mystring = "Hello (world)! It's _{now}_ or -- [never]...;")
    $mystring.replaceAll("</?([\W\s_]+)/?>", "");
    

    =>

    HelloworldItsnowornever