Javascript string.prototype.contains() with locale
Javascript string.prototype.contains() with locale
是否可以检查字符串是否包含具有区域设置支持的子字符串?
'Ábc'.contains('A')
应该为真。
Javascript现在有string.prototype. localecompare()用于字符串比较与地区支持,但我看不到localeContains()
对应的
你可以这样做:
String.prototype.contains = function contains(charToCheck) {
return this.split('').some(char => char.localeCompare(charToCheck, 'en', {sensitivity: 'base'}) === 0)
}
console.log('Ábc'.contains('A')) // true
console.log('Ábc'.contains('B')) // true
console.log('Ábc'.contains('b')) //true
console.log('Ábc'.contains('u')) //false
console.log('coté'.contains('e')) //true
localCompare的文档。灵敏度base
表示:
"base":只有基字母不同的字符串才会被视为不相等。示例:
a ≠ b
,a = á
,a = A
.
对于字符串
,有一个比contains()更快的选择,使用区域设置检查。似乎去掉变音符号然后本地比较字符串要快得多:在我的架构上,几乎比@chicken或@dag0310解决方案快10倍,请查看您的解决方案。在空字符串检查时返回true,以与String.includes
一致。
String.prototype.localeContains = function(sub) {
if(sub==="") return true;
if(!sub || !this.length) return false;
sub = ""+sub;
if(sub.length>this.length) return false;
let ascii = s => s.normalize("NFD").replace(/['u0300-'u036f]/g, "").toLowerCase();
return ascii(this).includes(ascii(sub));
}
var str = "142 Rozmočených Kříd";
console.log(str.localeContains("kŘi"));
console.log(str.localeContains(42));
console.log(str.localeContains(""));
console.log(str.localeContains(false));
如果你正在寻找一个以上的字符,这里是一个不是很有效但工作的选项:
const localeContains = (a,b) => !!a.split('').filter((v,i)=>a.slice(i,b.length).localeCompare(b, "en", { sensitivity: 'base' })===0).length
a = "RESERVE ME";
b = "réservé";
console.log(localeContains(a,b));
如果搜索的字符串不在主字符串的开头,则小鸡的答案不起作用。
用这个包代替:https://www.npmjs.com/package/locale-includes
localeIncludes('RESERVE ME', 'éservé', {usage: 'search', sensitivity: 'base'});
// true
作为字符串原型函数使用更方便:
String.prototype.localeIncludes = function(str) {
return localeIncludes(this, str, {usage: 'search', sensitivity: 'base'});
};
'RESERVE ME'.localeIncludes('éservé');
// true
相关文章:
- Fighting with FRP
- issue with FB.Event.subscribe
- geolocation-marker.js conflict with markerclusterer.js
- Angular 2.0 with JavaScript or TypeScript?
- 为什么不推荐使用“with”?是否有更好或其他方法可以“下降”到对象的命名空间
- WebComponentsJS with IE10
- 指令的模板必须只有一个根元素:With restrict E&替换true
- timeago.js with datatable and PHP
- Ajax and Json with Rails
- errors with Javascript try catch
- how to split a string with ','
- Understanding Javascript scope with "var that = this&qu
- Architecture for CPU intensive tasks with NodeJS & Socke
- How to declare a Map containing certain properties with flow
- 设置'这'在React with Inverse Data Flow中
- Unit-testing multiple use cases with Karma & Mocha.js
- Modify Javascript with C#
- 谷歌地图API v3:Initial View is Fine,but Gray Box with No Map if
- Bootstrap Datepicker Locale with MomentJS
- Javascript string.prototype.contains() with locale