-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcapitalizeWords.js
50 lines (40 loc) · 1.72 KB
/
capitalizeWords.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
(function($) {
$.fn.capitalizeWords = function() {
return this.each(function() {
var element = $(this);
function capitalizeWord(word) {
return word.replace(/(^[a-z])|([\s\(\)\$\.\#][a-z])/g, function(match) {
return match.toUpperCase();
});
}
if (element.is('input, textarea')) {
// Handle input and textarea elements
var input = element.get(0); // Get the DOM element
// Save the current cursor position
var start = input.selectionStart;
var end = input.selectionEnd;
var text = element.val();
var words = text.split(/\s+/);
for (var i = 0; i < words.length; i++) {
words[i] = capitalizeWord(words[i]);
}
element.val(words.join(' '));
// Restore the cursor position
input.setSelectionRange(start, end);
} else {
// Handle other elements like div, span, etc.
var textNode = element.contents().filter(function() {
return this.nodeType === 3; // Text node
}).get(0); // Get the first text node
if (textNode) {
var text = textNode.textContent;
var words = text.split(/\s+/);
for (var i = 0; i < words.length; i++) {
words[i] = capitalizeWord(words[i]);
}
textNode.textContent = words.join(' ');
}
}
});
};
})(jQuery);