Manipulating Text
Strings have many built-in methods for manipulation, searching, and transformation.
These methods make working with text data much easier.
const text = 'Hello World';
// Length
text.length; // 11
// Case conversion
text.toLowerCase(); // 'hello world'
text.toUpperCase(); // 'HELLO WORLD'
// Searching
text.includes('World'); // true
text.indexOf('World'); // 6
text.startsWith('Hello'); // true
text.endsWith('World'); // true
// Extracting
text.slice(0, 5); // 'Hello'
text.substring(6, 11); // 'World'
text.charAt(0); // 'H'
// Replacing
text.replace('World', 'JavaScript'); // 'Hello JavaScript'
// Splitting
'a,b,c'.split(','); // ['a', 'b', 'c']
// Trimming
' hello '.trim(); // 'hello'
// Repeating
'ha'.repeat(3); // 'hahaha'
// Template literals
const name = 'John';
const greeting = `Hello, ${name}!`; // 'Hello, John!'
- length - String length
- toLowerCase/toUpperCase - Change case
- includes/indexOf - Search string
- slice/substring - Extract portion
- replace - Replace text
- split - Convert to array
- trim - Remove whitespace
- Template literals - String interpolation
Try String Methods
<div class="string-demo">
<h3>Text Manipulator</h3>
<textarea id="textInput" placeholder="Enter some text...">Hello World! Welcome to JavaScript.</textarea>
<div class="buttons">
<button onclick="toUpper()">Uppercase</button>
<button onclick="toLower()">Lowercase</button>
<button onclick="reverseText()">Reverse</button>
<button onclick="countWords()">Count Words</button>
</div>
<div id="textOutput"></div>
</div>
Note: String methods don't modify the original string - they return a new string!