jQuery’s text replacement capabilities are essential skills for modern web developers. Whether you’re building dynamic content, implementing search functionality, or updating user interfaces, knowing how to replace text efficiently can significantly improve your web applications.
In this article, I will explain to you the Replacement of Text in a String in jQuery with examples.
jQuery Text Replacement
jQuery provides several methods to replace text within strings and HTML elements. The most common approaches include using the native JavaScript replace() method combined with jQuery selectors, the replaceWith() method, and specialized plugins designed for text manipulation.
Method 1: Use jQuery with JavaScript replace() Function
The easy approach combines jQuery’s text selection with JavaScript’s built-in replace() method.
Basic Syntax
$(selector).text(function(index, text) {
return text.replace('oldText', 'newText');
});Example 1: Simple Text Replacement
Replace a specific substring in an element’s text on user action.
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<p id="demo">Hello World! Welcome to our website.</p>
<button id="replaceBtn">Replace Text</button>
<script>
$('#replaceBtn').click(function() {
$('#demo').text(function(index, text) {
return text.replace('World', 'jQuery');
});
});
</script>
</body>
</html>You can see the output in the screenshot below.

This example replaces “World” with “jQuery” when the button is clicked.
Method 2: Use Regular Expressions for Advanced Replacement
Regular expressions provide powerful pattern matching for complex text replacement scenarios.
Example 2: Replace All Occurrences
Perform global or case-insensitive replacements across element text using regular expressions.
// Replace all occurrences (global replacement)
$('#content').text(function(index, text) {
return text.replace(/old/g, 'new');
});
// Case-insensitive replacement
$('#content').text(function(index, text) {
return text.replace(/hello/gi, 'Hi');
});Example 3: Replace Multiple Elements
Iterate over a set of elements and update each text content programmatically.
<div class="content">This is old content with old styling.</div>
<div class="content">Another old paragraph needs updating.</div>
<div class="content">The old system is being replaced.</div>
<script>
$('.content').each(function() {
$(this).text(function(index, text) {
return text.replace(/old/g, 'new');
});
});
</script>You can see the output in the screenshot below.

Method 3: Use jQuery replaceWith() Method
The replaceWith() method replaces selected elements with new content, including HTML tags.
Example 4: Replace Entire Elements
Swap out DOM elements wholesale with new HTML using `replaceWith()`.
<p class="old-paragraph">This paragraph will be replaced</p>
<script>
$('.old-paragraph').replaceWith('<div class="new-content">This is the new content!</div>');
</script>Method 4: Replace Text While Preserving HTML
When working with HTML content that contains tags, use the html() method instead of text():
Example 5: HTML-Aware Text Replacement
Modify element HTML while preserving markup, enabling inline replacements with HTML.
$('#container').html(function(index, html) {
return html.replace(/specific text/g, '<strong>highlighted text</strong>');
});You can see the output in the screenshot below.

Advanced Text Replacement Techniques
Let me explain to you some advanced text replacement techniques.
Example 6: Dynamic Text Replacement with User Input
Let users specify find/replace values and apply them across page content.
<input type="text" id="searchText" placeholder="Text to find">
<input type="text" id="replaceText" placeholder="Replace with">
<button id="performReplace">Replace</button>
<div id="content">
<p>This is sample content with various words to replace.</p>
<p>More sample text for demonstration purposes.</p>
</div>
<script>
$('#performReplace').click(function() {
var searchFor = $('#searchText').val();
var replaceWith = $('#replaceText').val();
if (searchFor && replaceWith) {
$('#content p').each(function() {
var currentText = $(this).text();
var newText = currentText.replace(new RegExp(searchFor, 'gi'), replaceWith);
$(this).text(newText);
});
}
});
</script>You can see the output in the screenshot below.

Example 7: Replace Text with Animation
Animate text changes by fading elements out, updating text, then fading them back in.
function animatedTextReplace(selector, oldText, newText) {
$(selector).fadeOut(300, function() {
$(this).text(function(index, text) {
return text.replace(oldText, newText);
}).fadeIn(300);
});
}
// Usage
animatedTextReplace('#myElement', 'old', 'new');Use jQuery Plugins for Text Replacement
For more sophisticated text replacement needs, specialized plugins offer additional functionality.
jQuery ReplaceText Plugin
// Using jquery-replacetext-plugin
$('#content').replaceText('oldText', 'newText');Best Practices and Performance Tips
Here are some best practices and performance tips for working with jQuery text replacement with a string.
1. Cache jQuery Objects
Store jQuery selections in a variable to avoid repeated DOM lookups when replacing text.
// Good practice
var $element = $('#myElement');
$element.text($element.text().replace('old', 'new'));
// Avoid multiple DOM queries
// $('#myElement').text($('#myElement').text().replace('old', 'new'));2. Use Document Ready
Ensure the DOM is loaded before running text-replacement code so elements exist and your replacements run reliably.
$(document).ready(function() {
// Your text replacement code here
$('.replaceable').text(function(index, text) {
return text.replace(/pattern/g, 'replacement');
});
});3. Error Handling
Wrap replacements in a try/catch to safely handle unexpected input or selector problems and log meaningful errors.
function safeTextReplace(selector, oldText, newText) {
try {
$(selector).text(function(index, text) {
return text ? text.replace(oldText, newText) : text;
});
} catch (error) {
console.error('Text replacement failed:', error);
}
}Real-World Use Cases
Let me show you the real-world use cases of jQuery replacement of text in a string.
Example 8: Content Localization
Replace currency symbols or locale-specific tokens to adapt content for different regions.
// Replace currency symbols for different regions
function localizeCurrency(region) {
var currencyMap = {
'US': '$',
'EU': '€',
'UK': '£'
};
$('.price').text(function(index, text) {
return text.replace(/\$|€|£/g, currencyMap[region]);
});
}Example 9: Highlight Search Terms
Wrap matched search terms in `<mark>` to visually highlight occurrences within HTML.
function highlightSearchTerms(searchTerm) {
$('.searchable').html(function(index, html) {
var regex = new RegExp('(' + searchTerm + ')', 'gi');
return html.replace(regex, '<mark>$1</mark>');
});
}jQuery text replacement is a powerful technique for creating dynamic, interactive web applications. Whether you’re using simple string replacement, regular expressions, or specialized plugins, these methods provide the flexibility needed for modern web development.
Remember to consider performance implications when working with large amounts of text, always test your regular expressions thoroughly, and implement proper error handling for production applications. With these techniques in your toolkit, you’ll be well-equipped to handle any text replacement challenges in your jQuery projects.
You may like to read:
- jQuery Set Hidden Field Value
- jQuery Validate Form Before Submit
- jQuery Disable Button After Click: With Examples

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.