0

i am using the below code

var value = 'abcd$';
var regularExpression= new RegExp('[-!$%^&*()_+|~=`{}\[\]:";\'<>?,.\/]');
if(regularExpression.test(value)) {
   //true
}
else{
false
}

it's returning false, even the string contains a special character.

2
  • Is the laste character "e" line 2 is normal ?
    – Badbaxx
    Feb 8, 2021 at 9:45
  • My bad, it's a typo mistake. I have edited my question. Thanks.
    – Anna
    Feb 8, 2021 at 9:57

2 Answers 2

0

Try this

<script>

var output;

var value = 'abcd$';
var regularExpression= new RegExp('^.*[-!$%^&*()_+|~=`{}[\\]:";\'<>?,.\/]+.*$');
if(regularExpression.test(value)) {
   output = 'true';
}else{
   output = 'false';
}

document.write(output);

</script>

The output

true
0

Here's another idea. I checked this in LWC component reference, and it works.

Template

<template>
 {has}
    <div class="slds-m-top_medium slds-m-bottom_x-large">
            <lightning-input type="text" onchange={check} label="Enter some text"></lightning-input>
    </div>
</template>

JS

import { LightningElement } from 'lwc';

export default class InputText extends LightningElement {
    has = false;

    check({detail}) {
        const value = detail.value
        this.has = /[-!$%^&*()_+|~=`{}\[\]:";\'<>?,.\/]+/.test(value);
    }
}

The difference is how I define RegExp. Not sure why this works and yours don't, digging into this. WIll update the answer once find out.

const regexp = /[-!$%^&*()_+|~=`{}\[\]:";\'<>?,.\/]+/

instead of

const regexp = new RegExp('[-!$%^&*()_+|~=`{}\[\]:";\'<>?,.\/]');

Also, I tried your way in a NodeJS REPL and it doesn't work either. SO it's not an LWC thing

Update There's a problem with your RegExp. You should escape backslashes, which escape other characters. So you need to have the RegExp constructed the following way

new RegExp('[-!$%^&*()_+|~=`{}\\[\\]:";\\\'<>?,.\/]')

instead of

new RegExp('[-!$%^&*()_+|~=`{}\[\]:";\'<>?,.\/]')

I would recommend using a string expression instead of constructing a RegExp object

/[-!$%^&*()_+|~=`{}\[\]:";\'<>?,.\/]+/

For more information look here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.