gpt4 book ai didi

javascript - 如何使用 jQuery 将 unicode 字符串转换为正确的字符?

转载 作者:行者123 更新时间:2023-11-30 20:52:41 25 4
gpt4 key购买 nike

这里我有以下函数将字符串转换为 slug 以制作 SEO 友好的 URL。

stringToSlug: function (title) {
return title.toLowerCase().trim()
.replace(/\s+/g, '-') // Replace spaces with -
.replace(/&/g, '-and-') // Replace & with 'and'
.replace(/[^\w\-]+/g, '') // Remove all non-word chars
.replace(/\-\-+/g, '-') // Replace multiple - with single -
}

var title1 = 'Maoist Centre adamant on PM or party chair’s post';
function stringToSlug1 (title) {
return title.toLowerCase().trim()
.replace(/\s+/g, '-') // Replace spaces with -
.replace(/&/g, '-and-') // Replace & with 'and'
.replace(/[^\w\-]+/g, '') // Remove all non-word chars
.replace(/\-\-+/g, '-') // Replace multiple - with single -
}
console.log(stringToSlug1(title1));

var title2 = 'घर-घरमा ग्यास पाइपः कार्यान्वयनको जिम्मा ओलीकै काँधमा !';

function stringToSlug2 (title) {
return title.toLowerCase().trim()
.replace(/\s+/g, '-') // Replace spaces with -
.replace(/&/g, '-and-') // Replace & with 'and'
.replace(/[^\w\-]+/g, '') // Remove all non-word chars
.replace(/\-\-+/g, '-') // Replace multiple - with single -
}
console.log(stringToSlug2(title2));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

这里我用两种不同的语言实现了上述功能。英语函数 stringToSlug1 和尼泊尔语函数 stringToSlug2。对于英文文本,该函数运行良好,但当文本为其他语言时,上述函数仅返回 - 。 我想从函数 stringToSlug2 获得的结果是ा-ओलीकै-काँधमा

最佳答案

不幸的是,正则表达式(JavaScript 中的正则表达式)的设计者在设计时并没有过多考虑国际化。 \w 只匹配 a-zA-Z_,所以 [^\w\- ]+ 表示 [^a-zA-Z_\-]+。正则表达式的其他方言具有启用 unicode 的单词模式,但 JavaScript 的最佳选择是有一个符号黑名单(你提到了 :!#@$$#@^%#^。你可以使用 [:!#@$$#@^%#^]+(而不是 [^\w\-]+)之类的东西来做到这一点。

关于javascript - 如何使用 jQuery 将 unicode 字符串转换为正确的字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48001933/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com