Reputation: 6285
Say, I have a text stored as:
var val1 = 'l-oreal';
I want to match val1
such that, it reads val1
and ignores hyphen (dash) in it. I want a regex that ignores special characters in a text. Is that possible?
I don't want to remove special character from the text. I want to ignore it.
Upvotes: 1
Views: 27528
Reputation: 4488
You can either use ^
in order to select your special characters then replace it to an empty string ''
, as:
val1.replace(/([^a-zA-z0-9]+)/g, s0 => ''); // loreal
All except a-zA-Z-0-9
will be removed.
Updated post for scenario when:
The string must contain characters abc and ignore any special characters
for this approach, you could make use of match to know if your string has any matches on your regex. If so, then you could use replace to switch special chars to empty string:
function strChecker(str) {
var response;
if(val1.match(/lorem/)) {
response = val1.replace(/([^a-zA-z0-9]+)/g, s0 => '');
}
return response;
}
strChecker('ha-ha?lorem') // returns hahalorem
strChecker('ha-ha?loram') // return undefined
Upvotes: 5
Reputation: 12737
var val1 = 'l-oreal';
var val2 = val1.replace(/\W/g,''); // remove any non-alphanumerics
console.log(val1); // still the same, not changed
console.log(val2); // only alphanumerics
Upvotes: 4
Reputation: 23869
You can match against the regex /[a-z]+/gi
and then join by a space or any other character:
var testString = "any string l-orem";
var matcher = /[a-z]+/gi;
var matches = testString.match(matcher);
var result = matches.join('');
console.log(result);
This, of course, doesn't change your original string, and can be simply customized to your own needs.
Upvotes: 5