Search code examples
javascripthtmlcssword-wrapword-break

Custom break word


I'm working on a map legend and I have some trouble when the word is too long. I want to know if it's possible to add some property to the text so it break to the last symbol space, score, underscore, slash, and other punctuation

In other words, I want more symbols to be interpret like spaces for the "default spaces breakline".

I try using word-wrap: break-word or word-break: break-all but it's not the expected result... It is what I want only if there is no symbol so I'll probably add 1 of these to the CSS to break lines (by the way I'm not sure about the differences / wich one to use / why)

Here's an example of what I would like (and what I tried)

http://jsfiddle.net/uazk54pL/

edit

by the way, I didn't use JavaScript because I thought it can be with css, and I'm not really sure how to do it... but I'm not against using it if no better solution is found

.tmp {
  border: black 1px solid;
  width: 100px;
  margin: 5px;
}
#wrap {
  word-wrap: break-word;
}
#break {
  word-break: break-all;
}
}
nothing
<div id="nothing" class="tmp">
  hi im/a-longword
  <br/>
  <br/>breaklineon-and_and and/
  <br/>
  <br/>ifnosymboliwantwordbreak
</div>
word-wrap: break-word;
<div id="wrap" class="tmp">
  hi im/a-longword
  <br/>
  <br/>breaklineon-and_and and/
  <br/>
  <br/>ifnosymboliwantwordbreak
</div>
word-break: break-all;
<div id="break" class="tmp">
  hi im/a-longword
  <br/>
  <br/>breaklineon-and_and and/
  <br/>
  <br/>ifnosymboliwantwordbreak
</div>
expected
<div id="expected" class="tmp">
  hi im/a-
  <br/>longword
  <br/>
  <br/>breaklineon-
  <br/>and_and and/
  <br/>
  <br/>ifnosymboli
  <br/>wantwordbr
  <br/>eak
</div>


Solution

  • I finally used the method tell in the question's comments. As my text is add with JavaScript, I'm just addind &thinsp; after special characters before add it to my page.

    str.replace(/([-/_])/g,"$&&thinsp;")
    

    Also I used the CSS word-wrap:break-word; to cut words too long