繁体   English   中英

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

[英]How to convert unicode string to proper character using jQuery?

在这里,我有以下函数将字符串转换为 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仅匹配azAZ_ ,因此[^\\w\\-]+表示[^a-zA-Z_\\-]+ 正则表达式的其他方言具有支持 unicode 的单词模式,但对 JavaScript 而言,最好的办法是拥有一个符号黑名单(您提到:!#@$$#@^%#^ 。您可以使用类似[:!#@$$#@^%#^]+ (而不是[^\\w\\-]+ )。

基于答案https://stackoverflow.com/a/18936783/5740382

我想出了一个解决方案,虽然这不是一个好的解决方案(我猜)。 我会用.replace(/([~!@#$%^&*()_+= {}[]\\|\\:;'<>,./? ])+/g, ' -') regex instead of filtering all non-word chars with .replace(/[^\\w-]+/g, '')` regex instead of filtering all non-word chars with 所以这是我的 jQuery 函数。

 var title = 'घर-घरमा ग्यास पाइपः कार्यान्वयनको जिम्मा ओलीकै काँधमा !'; function stringToSlug (title) { return title.toLowerCase().trim() .replace(/\\s+/g, '-') // Replace spaces with - .replace(/&/g, '-and-') // Replace & with 'and' .replace(/([~!@#$%^&*()_+=`{}\\[\\]\\|\\\\:;'<>,.\\/? ])+/g, '-') // Replace sepcial character with - .replace(/\\-\\-+/g, '-') // Replace multiple - with single - } console.log(stringToSlug(title));
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM