Word split removes spacing
coolemur opened this issue · 3 comments
coolemur commented
When I use
charming(element, {
splitRegex: /(\s+)/,
classPrefix: 'word'
})
to split words, spaces are removed. It looks like they are still in DOM, but aren't shown.
Is there a way to split words and keep spaces ?
xesjkeee commented
I've found a solution, it looks like this:
const titleNode = document.getElementsByClassName('title')[0]
charming(titleNode)
const charsNodeList = document.querySelectorAll('.title > span')
const charsArrayWithSpace = charsArray.filter(el => {
if (el.textContent === ' ') el.textContent = ' ' // Here's symbol  
return el
})
The idea is to change a usual space symbol to the narrow space symbol  
ronca85 commented
@coolemur hello!
you can use a non-breaking space instead of a space character in your html
turn <h1>My Title</h1>
into <h1>My Title</h1>
yuanqing commented
Is there a way to split words and keep spaces ?
The regular expression to use is /\b(?=\S)/
, which is a positive lookahead. This will split the string
on word boundaries (\b
) that occur immediately before any non-whitespace character (\S
)
<h1>foo bar baz</h1>
.word-1 {
color: red;
}
.word-2 {
color: green;
}
.word-3 {
color: blue;
}
const element = document.querySelector('h1')
charming(element, {
split: function (string) {
return string.split(/\b(?=\S)/)
},
setClassName: function (index) {
return `word-${index}`
}
})