[英]White list in str.replace
i'm using this code to replace everyone who has website link in they name change it to nothing eg 我正在使用此代码替换所有具有网站链接的人,他们将其名称更改为无,例如
Username - Somewebsite.com
-> Username -
Username - Somewebsite.com
> Username -
For that I use this code: 为此,我使用以下代码:
name.replace(/([a-zA-Z0-9\-]*\.com)/g, '');
But I want to make it so when user is using my website adress in their name to not remove it eg 但是我想做到这一点,以便当用户以他们的名义使用我的网站地址时不将其删除
Username - Mywebsitename.com
-> Username - Mywebsitename.com
Username - Mywebsitename.com
> Username - Mywebsitename.com
Easiest would be to just use a callback for replace()
and weed out matches on a certain string 最简单的方法是仅对replace()
使用回调,并清除特定字符串上的匹配项
var mySite = 'Somewebsite.com';
var name = "Username - Somewebsite.com";
var result = name.replace(/([a-zA-Z0-9\-]*\.com)/g, function(what) {
return what === mySite ? what : "";
});
Nearly pure regex solution: 几乎纯正则表达式的解决方案:
/\s+\-\s+(?!Mywebsite\.com)([a-zA-Z0-9\-]+)\.com/i
Working example: 工作示例:
var regex = /\\s+\\-\\s+(?!Mywebsite\\.com)[a-zA-Z0-9\\-]+\\.com/i var string = 'Username - Somewebsite.com' var output = 'Username -' console.log('Match:', string) console.log('Result:', string.replace(regex, ' -')) console.log('Correct:', (string.replace(regex, ' -') === output) === true) console.log('') // new line var string = 'Username - Mywebsite.com' var output = 'Username - Mywebsite.com' console.log('Match:', string) console.log('Result:', string.replace(regex, ' -')) console.log('Correct:', (string.replace(regex, ' -') === output) === true)
Regex Explanation: 正则表达式说明:
/ //-> open regex
\s+ //-> match one or more spaces
\- //-> match one literal dash
\s+ //-> match one or more spaces
(?!Mywebsite\.com) //-> look ahead & assert next match is not "Mywebsite.com"
([a-zA-Z0-9\-]+) //-> match one or more lower or upper case letter, digits, & dot
\. //-> match literal dot
c //-> match c
o //-> match o
m //-> match m
/ //-> close regex
i //-> make search case insensitive
Look behind would likely have been more ideal for this, but it's not supported in JavaScript. 往后看可能会更理想,但是JavaScript不支持。
I hope that helps! 希望对您有所帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.