说,我有一个文本存储为:
var val1 = 'l-oreal';
我想匹配val1
这样,它读取val1
并忽略其中的连字符(破折号)。我想要一个忽略文本中特殊字符的正则表达式。那可能吗?
我不想从文本中删除特殊字符。我想忽略它。
您可以匹配正则表达式/[a-z]+/gi
,然后通过空格或任何其他字符加入:
var testString = "any string l-orem";
var matcher = /[a-z]+/gi;
var matches = testString.match(matcher);
var result = matches.join('');
console.log(result);
当然,这不会改变您的原始字符串,可以根据您自己的需要进行定制。
您可以使用^
来选择特殊字符,然后将其替换为空字符串''
,如下所示:
val1.replace(/([^a-zA-z0-9]+)/g, s0 => ''); // loreal
除a-zA-Z-0-9
之外的所有将被删除。
方案的更新帖子:
该字符串必须包含字符abc并忽略任何特殊字符
对于这种方法,你可以利用匹配来知道你的字符串是否在你的正则表达式上有任何匹配。如果是这样,那么你可以使用replace来将特殊字符切换为空字符串:
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
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