fix generate slug, fixed #45

This commit is contained in:
qingwei.li 2016-12-31 14:16:15 +08:00
commit 9638eee50d
3 changed files with 35 additions and 4 deletions

View file

@ -1,3 +1,7 @@
## 1.4.1
### Bug fixes
- Fix generate slug.
## 1.4.0 Happly new year 🎉
### Features
- Display TOC in the custom sidebar, `data-sub-max-level`.

View file

@ -2,7 +2,7 @@ import marked from 'marked'
import Prism from 'prismjs'
import * as tpl from './tpl'
import { activeLink, scrollActiveSidebar, bindToggle, scroll2Top, sticky } from './event'
import { genTree, getRoute, isMobile } from './util'
import { genTree, getRoute, isMobile, slugify } from './util'
let OPTIONS = {}
const CACHE = {}
@ -21,9 +21,7 @@ const renderer = new marked.Renderer()
* @link https://github.com/chjj/marked#overriding-renderer-methods
*/
renderer.heading = function (text, level) {
const slug = text.toLowerCase()
.replace(/<(?:.|\n)*?>/gm, '')
.replace(/[^\w|\u4e00-\u9fa5]+/g, '-')
const slug = slugify(text)
let route = ''
if (OPTIONS.router) {

View file

@ -105,3 +105,32 @@ export function getRoute () {
export function isMobile () {
return document.body.clientWidth <= 600
}
export function slugify (string) {
const re = /[\u2000-\u206F\u2E00-\u2E7F\\'!"#$%&()*+,.\/:;<=>?@\[\]^`{|}~]/g
const maintainCase = false
const replacement = '-'
slugify.occurrences = slugify.occurrences || {}
if (typeof string !== 'string') return ''
if (!maintainCase) string = string.toLowerCase()
let slug = string.trim()
.replace(re, '')
.replace(/\s/g, replacement)
let occurrences = slugify.occurrences[slug]
if (slugify.occurrences.hasOwnProperty(slug)) {
occurrences++
} else {
occurrences = 0
}
slugify.occurrences[slug] = occurrences
if (occurrences) {
slug = slug + '-' + occurrences
}
return slug
}