簡體   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