I want to replace all "i" character in <body> with "I" by JavaScript.
(for example: <div id="123">Hi! it!</div> should change to <div id="123">HI! It!</div>).
I know I must use regular expressions. but I don't know what I should write.
Can you help me?
Thanks ..
-
1Why on earth do you want to do that?SLaks– SLaks2010-12-20 13:06:19 +00:00Commented Dec 20, 2010 at 13:06
-
6How do you know that you 'must' use regex?dheerosaur– dheerosaur2010-12-20 13:06:29 +00:00Commented Dec 20, 2010 at 13:06
-
Because I want to replace "i" with "I", only in contents and not in tags ...mrdaliri– mrdaliri2010-12-20 13:13:39 +00:00Commented Dec 20, 2010 at 13:13
-
3If it's HTML/XML, don't use regular expressions. Historic archives of Stackoverflow will tell you why.darioo– darioo2010-12-20 13:15:17 +00:00Commented Dec 20, 2010 at 13:15
-
@darioo: I begin to see you guys' point (and weariness).tchrist– tchrist2010-12-20 13:17:12 +00:00Commented Dec 20, 2010 at 13:17
2 Answers
I just answered a similar question which may help you: JQuery/Javascript - Search DOM for text and insert HTML
For this particular case, you can simplify.
UPDATE
I've added a filter parameter to allow you to filter out descendants of particular nodes. This should be a function that takes a single DOM node parameter and returns a Boolean: true to replace text within the node and its descendants and false to ignore the node and its descendants.
function replaceText(node, regex, replacementText, filter) {
if (node.nodeType == 3) {
node.data = node.data.replace(regex, replacementText);
} else if (!filter || filter(node)) {
var child = node.firstChild;
while (child) {
replaceText(child, regex, replacementText, filter);
child = child.nextSibling;
}
}
}
function scriptAndStyleFilter(node) {
return node.nodeType != 1 || !/SCRIPT|STYLE/i.test(node.nodeName);
}
replaceText(document.body, /i/g, "I", scriptAndStyleFilter);
11 Comments
<style> elements are not valid within the <body> element of an HTML document (even though it does work in most browsers).<style type="...">#myid {font-family: tahoma}</style><span id="myid">Hi! it!</span> I want it changed to this: <style type="...">#myid {font-family: tahoma}</style><span id="myid">HI! It!</span> (all of <style> contents must don't be changed)<style type="...">#myId {font-famIly: tahoma}</style><span id="myid">HI! It!</span>Here's an alternative, using CSS, jQuery and a Highlight plugin:
CSS:
.highlight {text-transform:uppercase;}
JavaScript:
$('body').highlight('i');
Working example: http://jsbin.com/okavo4
This is a quick example, but you can use the source code to get what you want, in case you need something more complex. Using a regular expression on the source of your body is wrong, specially in context of a browser, where you already have a parsed DOM structure.