[SalesForce] RegEx expression in Lightning Component seen issue even if its works in RegEx tool

Trying my hands on RegExp in lightning component.The regExp i've validated using https://regex101.com/ is working fine but fails to work in controller.js. Pls advice if am missing on anything.

Requirement : Need a particular char to be removed from the start and end of the string.

e.g :  var Str =  "~ ~~   ~~   ~The world is at peace~~  ~" ;
        var str1 = str.replace('^[~\\s+]+|[~\\s+]$','')   ;  <----- this fails to work on lightning comp

   **output expected : The world is at peace**
    Actual output:  ~ ~~   ~~   ~The world is at peace~~  ~

Do we've any documentation, that could help to know more on usage of RegExp in lightning? Also tried replacing '\\s' to '\\\\s'. Dint see it to bring any change.

Best Answer

It's not Lightning, it's your JavaScript. This doesn't work in Node or even a browser console on a blank tab.

The regex you want is:

str.replace(/^(~+\s*)+|(~+\s*)+$/g,'');

Note the /pattern/g format. The g means "global replace", otherwise you only get one match. You do not need to "double-escape" in JavaScript, either. The above code should work in LWC, Aura, or elsewhere.

Alternatively:

str.replace(new RegExp('^(~+\s*)+|(~+\s*)+$','g'),'');

This makes the string into a regular expression; this also works.

If you use just a normal string, it does not perform a regular expression replacement, but instead a normal string replacement (literal characters).

Finally, note that [...] is a character class, you meant to use a capture group (...). Otherwise you'll replace other things you didn't mean to.

Related Topic