|
|
| Databases 101 | | | ASP.NET Chapter | | | Suggest Article | | | Discussions | | | Bookstore | | | Write for Us | | | OpenAuction | | | Our Authors | |
|
|
|
Image & Video Software
IT Products
Manage Your E-Store
Add a Career Center
Buy Computer Products
Training Solutions
Document Management
Training Solutions
Add Online Sales Reps
Volume Licensing
|
 |
|
| Javascript Search and Replace | | by Pete Nelson | | | Skill level: Beginner | | | First posted: Sunday, December 10, 2000 | |  | |  | | Overview
Recently I was working on a browser-based content-management system and was often copying and pasting content into our site. In some cases, we needed to to bulk changes on this content (links, HTML, etc), and since the browsers only have a search feature and no replace, here's a Javascript function I whipped up that will let me do a search and replace.
Unfortunately Javascript doesn't have the same handy Replace() function like VB and VBScript, so what we do is use the .indexOf method (just like InStr in VB) on the string object to find our text. We then put everything before the match, the text to replace the match with and everything after the match into a temporary variable. We keep looping through all the content in the temporary variable, doing the replace as we go until there are no more matches (the .indexOx value is not greater that -1). Here's the function. Just pass it the string you want to search, what you're searching for and what to replace it with. It will return a string with the parsed content.
Code
function SearchAndReplace(Content, SearchFor, ReplaceWith) {
var tmpContent = Content; var tmpBefore = new String(); var tmpAfter = new String(); var tmpOutput = new String(); var intBefore = 0; var intAfter = 0;
if (SearchFor.length == 0) return;
while (tmpContent.toUpperCase().indexOf(SearchFor.toUpperCase()) > -1) { // Get all content before the match intBefore = tmpContent.toUpperCase().indexOf(SearchFor.toUpperCase()); tmpBefore = tmpContent.substring(0, intBefore); tmpOutput = tmpOutput + tmpBefore;
// Get the string to replace tmpOutput = tmpOutput + ReplaceWith;
// Get the rest of the content after the match until // the next match or the end of the content intAfter = tmpContent.length - SearchFor.length + 1; tmpContent = tmpContent.substring(intBefore + SearchFor.length);
}
return tmpOutput + tmpContent;
}
|
Try the sample!
|
| |  | |  |
This document can be found in these Encyclopedia chapters: º JavaScript
|
 |
|
 |
This is what people have been saying about this article:
Create a new discussion |
 |
|
 |
View Article Statistics
Authors... Edit this article View Preview Version
|
|
| Printable Copy of Article |
| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
|
|