-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathaction.js
68 lines (51 loc) · 1.83 KB
/
action.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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// 1Writer Title Case Action
// Adheres to John Gruber’s rules for title case
// http://daringfireball.net/2008/05/title_case
// Based on Paul Mucur’s Ruby implementation
// https://github.com/mudge/title_case
var smallWordsRegex =
/^(a|an|and|as|at|but|by|en|for|if|in|of|on|or|the|to|v\.?|via|vs\.?)$/;
function colonCheck(word) {
return (word[word.length - 1] === ':');
}
function titleizeIfAppropriate(word) {
var dotCheckRegex = /\w\.\w/;
var intercapCheckRegex = /^.+[A-Z]/;
if (!word.match(dotCheckRegex) && !word.match(intercapCheckRegex)) {
// Check that word begins with a letter before upcasing
if (word.match(/^\W*\w/)) {
word = word[0].toUpperCase() + word.substr(1);
}
}
return word;
}
function toTitleCase(text) {
var result = '';
var colonFlag = false; // Was the current word preceded by a colon?
var words = text.split(' ');
for (var i = 0; i < words.length; i++) {
var formattedWord = '';
if ((i === 0) || (i === words.length - 1) ||
(colonFlag) || (colonCheck(words[i]))) {
// Titleize first words, last words, first words after colons,
// and last words before colons regardless of whether
// they are small words
formattedWord = titleizeIfAppropriate(words[i]);
} else if (words[i].match(smallWordsRegex)) {
// If none of these boundaries apply,
// but word is a small word, downcase
formattedWord = words[i].toLowerCase();
} else {
// All other words titleized if appropriate
formattedWord = titleizeIfAppropriate(words[i]);
}
result += formattedWord + ' ';
colonFlag = colonCheck(words[i]);
}
result = result.substr(0, result.length - 1); // chop trailing space
return result;
}
// ACTION
var selectedText = editor.getSelectedText();
var formattedText = toTitleCase(selectedText);
editor.replaceSelection(formattedText);