Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to allow long and unbreakable words to be broken and wrap to the next line in JavaScript?
Use the wordWrap CSS property in JavaScript to allow long and unbreakable words to be broken and wrap to the next line. This property is especially useful when dealing with long URLs, email addresses, or continuous text that would otherwise overflow their container.
Syntax
element.style.wordWrap = "break-word";
wordWrap Property Values
| Value | Description |
|---|---|
normal |
Default behavior - only break at allowed break points |
break-word |
Break long words anywhere to prevent overflow |
Example
The following example demonstrates how to use the wordWrap property to break long words that exceed the container width:
<!DOCTYPE html>
<html>
<head>
<style>
#box {
width: 150px;
height: 150px;
background-color: lightblue;
border: 1px solid black;
padding: 10px;
}
</style>
</head>
<body>
<button onclick="display()">Break Long Words</button>
<button onclick="reset()">Reset</button>
<div id="box">
ThisisDemoText.ThisisDemoText.ThisisDemoText.ThisisDemoText.ThisisDemoText.ThisisDemoText.
</div>
<script>
function display() {
document.getElementById("box").style.wordWrap = "break-word";
}
function reset() {
document.getElementById("box").style.wordWrap = "normal";
}
</script>
</body>
</html>
How It Works
When wordWrap: "break-word" is applied:
- Long words that exceed the container width are broken at any character
- The broken part wraps to the next line
- This prevents horizontal scrolling and maintains layout integrity
Alternative: word-break Property
For more control over word breaking behavior, you can also use the word-break property:
<!DOCTYPE html>
<html>
<head>
<style>
.container {
width: 200px;
border: 1px solid #ccc;
padding: 10px;
margin: 10px 0;
}
</style>
</head>
<body>
<div class="container" id="example1">
supercalifragilisticexpialidocious
</div>
<button onclick="applyBreakAll()">Apply break-all</button>
<script>
function applyBreakAll() {
document.getElementById("example1").style.wordBreak = "break-all";
}
</script>
</body>
</html>
Comparison
| Property | Breaking Behavior | Best Use Case |
|---|---|---|
wordWrap: break-word |
Breaks only when necessary | URLs, long identifiers |
word-break: break-all |
Breaks aggressively at any character | Dense text in narrow containers |
Conclusion
The wordWrap property with break-word value effectively handles overflow from long unbreakable words. Use it to maintain responsive layouts and prevent horizontal scrolling in constrained containers.
