Return everything after the first occurrence of a string in another string. Returns an integer count of occurrences, with 0 indicating no occurrences were found..
Suffix each word in a string with a string of text.
the text to suffix each word with.
// Example
alert("one, two, and three.".TA_appendWords("**"));
//Displays "one**, two**, and** three**."
Create a space padded box around the string. Returns the string for the box and original string combination. This function will handle multiline strings.
the string used to create the top of the box, excluding the corners.
the string used to create the bottom of the box, excluding the corners.
the string used to create the left side of the box, excluding the corners.
the string used to create the right side of the box, excluding the corners.
the string used to create the top left corner of the box.
the string used to create the top right corner of the box.
the string used to create the bottom left corner of the box.
the string used to create the bottom right corner of the box.
// Example
"Example Text\nMore content, diferent length".TA_boxer("v", "^", ">", "<", "/", "\\", "\\", "/");
The example generates a box like this:
/vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv\
> Example Text <
> More content, different length <
\^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^/
Create a space padded box around the string using double line characters. Returns the string for the box and original string combination. This function will handle multiline strings.
// Example
"Example Text\nMore content, diferent length".TA_boxerDouble();
The example generates a box like this:
╔════════════════════════════════╗
║ Example Text ║
║ More content, different length ║
╚════════════════════════════════╝
Create a space padded box around the string using single line characters. Returns the string for the box and original string combination. This function will handle multiline strings.
// Example
"Example Text\nMore content, diferent length".TA_boxerSingle();
The example generates a box like this:
┌────────────────────────────────┐
│ Example Text │
│ More content, different length │
└────────────────────────────────┘
Capitalise each word in a string based on a word separator being in place. This isn't a perfect implementation (notice the example below using "isn't"), but it is typically good enough, and it does leave existing capital letters in place (again, see the example below).
// Example
alert("there isn't I in team, but there is me in tEaM if you look closely".TA_capitalise());
//Displays "There Isn'T I In Team, But There Is Me In TEaM If You Look Closely"
Open a Markdown URL from the string.
The function identifies Markdown links in the string (excluding image links) and displays a list of link titles to the
user. When the user selects a title, the function will then attempt to open the corresponding URL.
If an attempt is made to open a URL, the function returns true
, otherwise it returns false
.
when true
, causes the list of links to be deduplicated before display. Defaults to true
.
when true
, will display a message if no Markdown links are found. Deafults to false
.
// Example
strLotsOfText.TA_chooseAndOpenMDLink();
Counts lines the number of lines in the string.
// Example
alert("foo bar".TA_countLines(0));
// Displays 1
Pass in a base of 0 or 1 for how many lines an empty string counts as, defaults to 0.
Count occurences of one string in another. Paramters allow the links to be sorted alphabetically and deduplicated. Returns an integer count of occurrences, with 0 indicating no occurrences were found..
the text string to be matched within the searched string.
defaults to false
, but when set to true
, will apply a case sensitive match.
// Example
"abcdefabc".TA_countOccurrences("Abc", false);
Counts the number of words in the string
// Example
alert("foo bar".TA_countWords());
// Displays 2
Split a string of comma separated values into an array. Handles whitespace, a mixture of double quoted and non-double quoted elements, and commas within double quoted elements. Returns an array with double quote delimiters removed.
// Example
alert(` abc , "def" ,"gh,i"`.TA_csvToArray().join("|"));
// Displays: abc|def|gh,i
Add text strings to the start and end of every string in a string of comma separated values. Rather than just splitting the string by commas, this function respects any whitespace based padding alongside the commas. For example, a list of words in English would have spaces after the commas. It also will automatically try and account for entries also being double quoted if it finds a double quote before the first entry. In such a case, it will put the prefix and suffix strings within the double quotes. Parameters are provided that can enforce one mode or the other. Attempting to force both will simply return an unmodified string. The function otherwise returns the updated string. The function will not accurately process strings that contain a mixture of double quoted and non-double quoted entries.
the text string to put at the start of every item in the list.
the text string to put at the end of every item in the list.
forces the function to assume all CSV entries are wrapped in double quotes. Defaults to false
.
forces the function to assume all CSV entries are not wrapped in double quotes. Defaults to false
.
// Example
alert("Red apples, yellow bananas , orange oranges ,green pears".TA_csvWrap("[", "]"));
Convert all entries in a CSV string to double quoted entries. Rather than just splitting the string by commas, this function respects any whitespace based padding alongside the commas. For example, a list of words in English would have spaces after the commas. It will leave existing double quoted entries untouched, and will only double quote unquoted items.
// Example
alert(`"Red apples", "yellow bananas" , orange oranges ,"green pears"`.TA_csvWrapDoubleQuotes());
//Displays `Red apples", "yellow bananas" , "orange oranges" ,"green pears"`
Decrypt an AES encrypted string. This is a key-based encryption and uses the crypto-js library to do the decryption. Please choose an appropriate AES key length when encrypting (128/192/256-bit) - e.g. a 64 character hexadecimal string for 256-bit encryption.
the encryption key used in the AES algorithm.
// Example
const ENCRYPTION_KEY = "FFEEDDCCBBAA99887766554433221100";
let strMessage = "Text to be encrypted";
let strEnc = strMessage.TA_encryptAES(ENCRYPTION_KEY);
alert("128-bit keyed encryption of message = " + strEnc);
let strDec = strEnc.TA_decryptAES(ENCRYPTION_KEY);
alert("Decrypted Message = " + strDec);
Decrypt an AES encrypted string and place it on the clipboard. This is a key-based encryption and uses the crypto-js library to do the decryption. Please choose an appropriate AES key length when encrypting (128/192/256-bit) - e.g. a 64 character hexadecimal string for 256-bit encryption.
the encryption key used in the AES algorithm.
// Example
const ENCRYPTION_KEY = "FFEEDDCCBBAA99887766554433221100";
let strMessage = "Text to be encrypted";
strMessage.TA_encryptAESOntoClipboard(ENCRYPTION_KEY);
alert("128-bit keyed encryption of message = " + app.getClipboard());
app.getClipboard().TA_decryptAESOntoClipboard(ENCRYPTION_KEY);
alert("Decrypted Message = " + app.getClipboard());
Deduplicates lines, retaining the original order of first occurrence. Returns the deduplicated string of text lines.
// Example
let strTest = "aa\naa\naa\nbb\ncc\naa";
alert(strTest.TA_deduplicateLines());
//Returns:
//aa
//bb
//cc
Delimit each word in a string with a string of text.
the text to prefix and suffix each word with.
// Example
alert("one, two, and three.".TA_delimitWords("*"));
//Displays "*one*, *two*, *and* *three*."
Reformat the string as a JavaScript string.
This uses a version of the js-beautifier library. It's a little
outdated, but functional for now and may be updated in the future to work with a newer library. Provision has been
made for this via the library settings which hold an update location for the library. Default setings will be used
unless a JSON file is present (name specified by beautifierSettings
library property) in the /Library/Scripts
folder
in Drafts, or if the parameter is passed in via the parameter. The order of priority is the parameter, followed by the
settings file, followed by the library default settings. Whatever settigns take priority, those settings will be passed to the beautification function. The
default settings are available on GitHub
for the js-beautifier information, and en example alternative configuration is shown below.
Please note that this function should only be run on a string containing JavaScript. If this function is run on
non-JavaScript, then the results could well be rather unexpected.
The function returns the reformatted code.
an optional set of Beautifier.js
settings expressed as a JSON object. Default is undefined
.
{
"indent_size" : 1,
"indent_char" : "\t",
"indent_with_tabs" : true,
"eol" : "\n",
"end_with_newline" : false,
"indent_level" : 0,
"preserve_newlines" : true,
"max_preserve_newlines" : 10,
"space_in_paren" : false,
"space_in_empty_paren" : false,
"jslint_happy" : false,
"space_after_anon_function" : false,
"brace_style" : "expand",
"unindent_chained_methods" : false,
"break_chained_methods" : false,
"keep_array_indentation" : false,
"unescape_strings" : false,
"wrap_line_length" : 0,
"e4x" : false,
"comma_first" : false,
"operator_position" : "before-newline",
"eval_code" : false,
"space_before_conditional" : true
}
// Example
alert(strUnformattedJavaScript.TA_devBeautifyJS());
Applies a more extensive set of URL encoding to a set of characters than encodeURIComponent()
.
The function also encodes all characters as per encodeURIComponent()
, and in addition, by default, it encodes !
, '
, *
, ~
, (
, and )
.
The encoding is defined by the TadLibrary
property encodeMap
, and is a set of key value pairs - the key being the character to be
encoded and the value being it's encoded value. If you should need to extend the range of characters encoded by this function, simply add
the necessary key value pairs to your library settings file.
// Example
let strText = "Some 100% *AMAZING!* text to (hopefully) encode."
alert(encodeURIComponent(strText));
// Displays "Some%20100%25%20*AMAZING!*%20text%20to%20(hopefully)%20encode."
alert(strText.TA_encodeURI());
// Displays "Some%20100%25%20%2AAMAZING%21%2A%20text%20to%20%28hopefully%29%20encode."
Encrypt a string using AES encryption. This is a key-based encryption and uses the crypto-js library to do the encryption. Please choose an appropriate AES key length when encrypting (128/192/256-bit) - e.g. a 64 character hexadecimal string for 256-bit encryption.
the encryption key used in the AES algorithm.
// Example
const ENCRYPTION_KEY = "FFEEDDCCBBAA99887766554433221100";
let strMessage = "Text to be encrypted";
let strEnc = strMessage.TA_encryptAES(ENCRYPTION_KEY);
alert("128-bit keyed encryption of message = " + strEnc);
let strDec = strEnc.TA_decryptAES(ENCRYPTION_KEY);
alert("Decrypted Message = " + strDec);
Encrypt a string using AES encryption and place it on the clipboard. This is a key-based encryption and uses the crypto-js library to do the encryption. Please choose an appropriate AES key length when encrypting (128/192/256-bit) - e.g. a 64 character hexadecimal string for 256-bit encryption.
the encryption key used in the AES algorithm.
// Example
const ENCRYPTION_KEY = "FFEEDDCCBBAA99887766554433221100";
let strMessage = "Text to be encrypted";
strMessage.TA_encryptAESOntoClipboard(ENCRYPTION_KEY);
alert("128-bit keyed encryption of message = " + app.getClipboard());
app.getClipboard().TA_decryptAESOntoClipboard(ENCRYPTION_KEY);
alert("Decrypted Message = " + app.getClipboard());
If a string ends with a specific sub string, this returns the string with that part removed. The original string is otherwise returned unchanged.
the sub string to remove from the end of the string if it matches.
// Example
alert(`abcd`.TA_endsWithRemove("cd");
// Displays: ab
Write a string to a destination file in the Mac file system. This function uses a shell script and so will only work on the Mac. It outputs a file to the Drafts iCloud sandboxed directory and then uses a shell script to move the file to the specified file path.
the file path the string should be written to.
// Example
"Example Text".TA_exportFileMac("$HOME/Desktop/example.txt");
Return the base name of a file from a file path or file name. This is the file name without the file extension.
// Example
alert("/Library/Scripts/main.sub.html".TA_fileNameBaseFromPath());
// returns "main.sub"
Return the file extension of a file from a file path or file name. This is whatever follows the base file name in the file name, excluding the period separator. If the file has no extension, an empty string will be returned.
// Example
alert("/Library/Scripts/main.sub.html".TA_fileNameExtensionFromPath());
// returns "html"
alert("/Library/Scripts/noext".TA_fileNameExtensionFromPath());
// returns ""
Return the file name from a file path. This includes both the base file name and the file extension.
// Example
alert("/Library/Scripts/main.sub.html".TA_fileNameFromPath());
// returns "main.sub.html"
Remove the file extension of a file from a file path or file name. The file extension is whatever follows the base file name in the file name, excluding the period separator.
// Example
alert("/Library/Scripts/main.sub.html".TA_fileNameRemoveExtensionFromPath());
// returns "/Library/Scripts/main.sub"
Fix a poorly formatted string of JavaScript from Discourse. If JavaScript code is posted on a Discourse forum outside of a code block, it will introduce smart quotes and lose formatting. This function will replace smart quotes (all of them, so if the code used them purposefully this needs a manual fix) and apply a JavaScript Beautification function to format the code. The function returns the reformatted code.
// Example
alert(`alert(“hello world”)`.TA_fixPoorDiscourseJavascript();
Return the folder path from a file path. This is the file path without the file name, but including the trailing slash. If you pass a folder path in with no trailing slash, the function will return the parent folder of the final folder in the path.
// Example
alert("/Library/Scripts/main.sub.html".TA_folderPathFromPath());
// returns "/Library/Scripts/"
alert("/Library/Scripts".TA_folderPathFromPath());
// returns "/Library/"
Takes a drafts action URL and converts it into something slightly more human readable. The string is URL decoded, and tab & newl ine markers are replaced with tab and new line characters respectively. The resulting string is returned.
// Example
let strURL = "drafts5://action?data=%7B%22uuid%22:%22C52192C1-4CB7-4C54-AE93-B8592D97CE64%22,%22steps%22:%5B%7B%22platforms%22:3,%22data%22:%7B%22template%22:%22%5B%5Bdraft%5D%5D%22%7D,%22type%22:%22clipboard%22,%22isEnabled%22:true,%22uuid%22:%22D7D0D0DB-95B8-4345-B40C-8E3F872D5612%22%7D%5D,%22groupDisposition%22:0,%22shortName%22:%22Copy%22,%22shouldConfirm%22:false,%22disposition%22:3,%22keyCommand%22:%7B%22optionKey%22:false,%22input%22:%22%22,%22controlKey%22:false,%22commandKey%22:false,%22type%22:%22action%22,%22discoverabilityTitle%22:%22Copy%22,%22shiftKey%22:false%7D,%22logLevel%22:2,%22notificationType%22:2,%22tintColor%22:%22none%22,%22actionDescription%22:%22Copy%20draft%20to%20clipboard.%22,%22keyUseIcon%22:false,%22icon%22:%22action_clipboard_filled%22,%22visibility%22:480,%22groupUUID%22:%22A1DEB68B-98DC-498C-9A12-137A9EA8FBF3%22,%22assignTags%22:%5B%5D,%22name%22:%22Copy%22%7D";
alert(strURL.TA_formatDraftsActionLinkToRead());
Carries out some basic checks to try and establish if there is a front matter section at the start of the string.
The function checks to see if the string begins with a triple dash and has a subsequent triple dash line to mark the end
of a front matter section. If it does, it checks to ensure that the lines in the section are either a key (text followed by a colon),
a list item (a hyphen, followed by a space, followed by some text), or a comment (an octothorpe, followed by a space, followed by
some text). Each of these may be preceded by whitespace, and blank lines are also permitted.
This is a fairly simple function intended only to verify the simplest sets of front matter. Full YAML testing is not carried
out, but this may be epanded in the future.
Returns true
if the criteria are matched, otherwise false.
// Example
alert(draft.content.TA_frontMatterIncluded());
Retrieves a front matter value from the string for a specified simple key. Here 'simple key' indicates that it is a root-level key and will appear at the start of a line. The returned value for the key is trimmed of any leading whitespace, and if there is no front matter, or no matching key (please note that it is case sensitive), an empty string is returned.
the name of the simple key whose value is to be returned.
// Example
alert(draft.content.TA_frontMatterSimpleKeyValue("author"));
Get e-mail addresses from a string. Returns an array of e-mail addresses. The array is not deduplicated, but the order of entries will match the order they occur in the string.
// Example
let strContent = `abc@def.com, is an email address as is def@abc.com\nnot to mention a@b.com.`;
alert(strContent.TA_getEmailAddresses().join("\n"));
Returns first character of the string.
// Example
alert("foo bar".TA_head());
// Displays "f"
When the string is an HTML string it returns the content between the first instance of the specified tag pair. Returns the string stripped of such content.
the name of the tag to locate the first instance of.
// Example
let strHTML = "<html><head><title>Foo Bar</title></head><body>Lorem ipsum dolor sit amet</body></html>";
strPageTitle = strHTML.TA_htmlFirstTagContent("title");
// Returns `Foo Bar`
When the string is an HTML string it returns the content between the first instance of the title tag pair. Returns the string stripped of such content.
// Example
let strHTML = "<html><head><title>Foo Bar</title></head><body>Lorem ipsum dolor sit amet</body></html>";
strPageTitle = strHTML.TA_htmlTitle();
// Returns `Foo Bar`
Return the string with the the specified text inserted after the specified 0-based index.
the position index of the character after which the text should be inserted. The first character is at position 0.
the text to be inserted.
// Example
alert("123456789".TA_insertAfter0(3, "qwerty"));
// Displays "1234qwerty56789"
Return the string with the the specified text inserted after the specified 1-based index.
the position index of the character after which the text should be inserted. The first character is at position 1.
the text to be inserted.
// Example
alert("123456789".TA_insertAfter1(3, "qwerty"));
// Displays "123qwerty456789"
Checks if a string is valid JSON.
Returns true
only if the string is valid JSON.
// Example
let strGoodJSON = '{"foreground" : "white", "background" : "black"}';
alert(strGoodJSON.TA_isJSON());
//Displays `true`
let strBadJSON = '{"foreground" : "white, "background" : "black"}';
alert(strBadJSON.TA_isJSON());
//Displays `false`
Counts the number of characters in the string, but new lines are excluded.
// Example
alert("foo bar".TA_lengthExclLineBreaks());
Returns an array of Markdown link substrings from a string.
The function identifies Markdown links in the string (excluding image links) and returns an array of those links - e.g.
["[foo](https://www.foo.com", "[bar](https://www.bar.com)"]
.
when true
, causes the array of links to be deduplicated before being returns. Defaults to true
.
// Example
strLotsOfText.TA_matchMDLinks();
Wrap a string in single backticks for a Markdown span of code.
// Example
alert(strCode.TA_mdCode());
Wrap a string in triple backticks for a Markdown block of code. Accepts an optional parameter to set a code type for syntax highlighting.
the text to insert after the first set of triple backticks that is used to set syntax highlighting where available. Default is none.
// Example
alert(strCode.TA_mdCodeBlock());
Wrap a string in triple backticks for a Markdown block of AppleScript.
// Example
alert(strCode.TA_mdCodeBlockAS());
Wrap a string in triple backticks for a Markdown block of JavaScript.
// Example
alert(strCode.TA_mdCodeBlockJS());
Wrap a string in triple backticks for a Markdown block of shell script.
// Example
alert(strCode.TA_mdCodeBlockSH());
Renumbers existing Markdown numbering at the start of lines in the string. Indented numbering is ignored, this function is 'simple' in that it only processes top/root level numbering. Additionally, if there are non-numbered lines of any sort, including blank lines, the function will simply continue numbering regardless. This really is just a simple renumbering function, but it is sufficient for renumbering in most cases for most users.
// Example
alert("3. First\n1. Second\n5. Third".TA_mdSimpleRenumber());
Convert all non-linked URLs as Markdown links using the page name as the title.
The function finds URLs in the string and uses the prior two characters to determine if it
is part of a Markdown link (preceded by ](
), or an HTML source (preceded by ="
). If
it is not preceded by these, the URL will be used to fetch the page title. That title is
then used to build a Markdown link which will replace all occurrences in the string of the URL.
Note, each unique URL is only fetched once to ensure that the function runs faster.
Returns the updated string.
// Example
let strTest = `https://getdrafts.com | [Forum Link]](https://forums.getdrafts.com) | (https://scripting.getdrafts.com) <a href="https://docs.getdrafts.com">Docs</a>`
alert(strTest.TA_mdTitleLinks());
// Displays: [Drafts | Where Text Starts](https://getdrafts.com) | [Forum Link]](https://forums.getdrafts.com) | ([Drafts Script Reference](https://scripting.getdrafts.com)) <a href="https://docs.getdrafts.com">Docs</a>
Convert a MultiMarkdown string to a plain text string. Returns the converted string.
// Example
alert("# Heading\nThen some **bold text**. \nThen some *italic text*.".TA_mdToText());
Replace new lines to merge a string into one line. Effectively concatenates multiple lines into one line (assuming the 'spacer' parameter does not contain a new line). The default character to concatenate lines with is a space, but can be set to any string. The function also allows an aray of exceptions to be specified, whereby if a line ends with one of those string, no spacer will be added. This can be further modified by a similar array that can specify when a line ending with a particular character string will always force a spacer to be included. The function returns the modified, merged string.
the string to use when joining two lines with a 'spacer'. Defaults to a single space character.
determines if lines should be trimmed of whitespace before joining. This defaults to true
.
an array of line endings where the next line should be joined to the current one with no 'spacer'. Defaults to an array including a hyphen, em dash, en dash and forward slash.
an array of line endings where the next line should always be joined to the current one with a 'spacer'. Defaults to an empty array.
// Example
let strOriginal = "foo bar\nbaz quz-\nqux";
alert(strOriginal.TA_mergeLines());
//Returns `foo bar baz quz-qux`
Mistype a set of characters in the string based on a statistical likelihood and some data driven rules.
The function purposefully messes up the typing in a string by potentially mistyping one in every p_intOneIn
characters. The lower
that value, the more likely a mistype will be. Mistypable characters are defined by being listed in p_strShiftable
. All such characters should then be
defined as keys in the JSON object, p_jsonSlipDefinition
, each having a value listing the characters it could slip to. The chance of slipping to any of
the characters is equal. To increase the likelihood of a character, simply repeat it in the string enough times to appropriately weight it for being
chosen at random. A mistyped version of the original string is returned.
the maxiumum random number used for generating a one in N chance of a character being potentially mistyped.
a JSON object with keys for each character that can be mistyped and a string of characters randomly chosen to replace it
a string listing the characters that can be mistyped.
// Example
let strTest = `Alan Aardvary attacked Ada Ant.`;
let jsonSimple = {};
jsonSimple.a = "qsssz";
jsonSimple.t = "rry";
alert(strTest.TA_mistypeSlip(3, jsonSimple, "at"));
//Example output: Alsn Sardvsry atracked Ada Ant.
Mistype a set of characters in the string based on a basic QWERTY keyboard.
The function purposefully messes up the typing in a string by potentially mistyping one in every p_intOneIn
characters. The lower
that value, the more likely a mistype will be. A mistyped version of the original string is returned.
the maxiumum random number used for generating a one in N chance of a character being potentially mistyped.
// Example
alert("The quick brown fox jumped over the lazy dog.".TA_mistypeSlipQWERTY(5));
//Example output: Thw quick briwn fox jumped over the lszt dog.
Mistype a set of characters in a string by transposing every one in N characters with its previous neighbour in the string.
The function purposefully messes up the typing in a string by potentially transposing one in every p_intOneIn
characters. The lower
that value, the more likely a mistype will be. A mistyped version of the original string is returned.
the maxiumum random number used for generating a one in N chance of a character being potentially mistyped.
// Example
alert("The quick brown fox jumped over the lazy dog.".TA_mistypeSwitch(5));
//Example output: The quikc bornwf o xujmped voe rth eazlyd og.
Return the string with the specified 0-based range replaced by the specified replacement text.
the position index of the first character in the range to be replaced. The first character is at position 0.
the position index of the last character in the range to be replaced. The first character is at position 0.
the text to use for the replacement.
// Example
alert("123456789".TA_overwriteRange0(3, 5, "qwerty"));
// Displays "123qwerty789"
Return the string with the specified 1-based range replaced by the specified replacement text.
the position index of the first character in the range to be replaced. The first character is at position 1.
the position index of the last character in the range to be replaced. The first character is at position 1.
the text to use for the replacement.
// Example
alert("123456789".TA_overwriteRange1(3, 5, "qwerty"));
// Displays "12qwerty6789"
Returns the original text with an "s" on the end when the numeric value passed in is not 1. Useful when passing in a count such that if it is greater than 1 it will add the "s".
// Example
alert("foo".TA_pluralise(6));
// Displays "foos"
Number related to the string. Greater than 1 will cause an s
to be added to the string.
Prefix each word in a string with a string of text.
the text to prefix each word with.
// Example
alert("one, two, and three.".TA_prependWords("**"));
//Displays "**one, **two, **and **three."
Process each line with another function. The called function should be a string processing funciton and return a string for the final result; assuming you wish to process a final combined result, otherwise it can effectively be ignored. Returns the processed result as a string.
the function that should be used to process each line.
// Example
function hi(strName)
{
return "Hello " + strName;
}
alert("John\nJane".TA_processLinesFunction(hi));
Returns a random character from the string.
// Example
let strTest = `qwertyuiopasdfghjklzxcvbnm`;
alert(strTest.TA_randChar());
Return a random line from a string.
// Example
alert(`An old silent pond...\nA frog jumps into the pond,\nsplash! Silence again.`.TA_randomLine();
Searches the string for the first index of a regular expression based match.
Returns the zero-based position in the original string (see p_intStartAt).
A return of -1
indicates that the no regular expression match was found.
Regular expression to match against.
Start position from which to begin searching. Defaults to 0.
// Example
alert("lorem sit ipsum sit dolor sit amet sit magna lectus".TA_regexIndexOf(/s(.*)t/,18));
// Displays "26"
Searches the string for the last index of a regular expression based match.
Returns the zero-based position in the original string (see p_intStartAt).
A return of -1
indicates that the no regular expression match was found.
Regular expression to match against.
Start position from which to begin searching backwards. Defaults to end of string.
// Example
alert("lorem sit ipsum sit dolor sit amet sit magna lectus".TA_regexLastIndexOf(/s(.*)t/,20));
// Displays "16"
Removes lines containing no content, or whitespace only. Returns the string stripped of such lines.
// Example
strCleaned = strTooManyBlanks.TA_removeBlankLines();
Removes lines containing no content. Returns the string stripped of such lines.
// Example
strCleaned = strWithEmptyLines.TA_removeEmptyLines();
Remove lines containing a particular string of text.
The text to match for removal is passed in along with an optional case sensitivity option.
The matching is based on regular expressions, so you must escape any regular expression special characters when passing them in.
You can always make use of the RegExp.TA_escape()
function to do this.
Returns the resulting text.
the string when found in a line constitutes a match for removal.
when true
(the default), text matches will be case sensitive, and when false
, the matches will be case insensitive.
// Example
let strLines = `apple starts line one
line two ends with apple
line three has apple in it
there are no fruits in line four
line five has an apple in it
line six ends with apple
apple starts line seven
there are no fruits in line eight`;
app.setClipboard("LINES NOT CONTAINING\n\n" + strLines.TA_removeLinesContaining("apple"));
// Displays the following:
// LINES NOT CONTAINING
//
// there are no fruits in line four
// there are no fruits in line eight
Remove lines ending with a particular string of text. The text to match for removal is passed in along with an optional case sensitivity option. Returns the resulting text.
the string when found at the end of a line constitutes a match for removal.
when true
(the default), text matches will be case sensitive, and when false
, the matches will be case insensitive.
// Example
let strLines = `apple starts line one
line two ends with apple
line three has apple in it
there are no fruits in line four
line five has an apple in it
line six ends with apple
apple starts line seven
there are no fruits in line eight`;
app.setClipboard("LINES NOT ENDING\n\n" + strLines.TA_removeLinesEnding("apple"));
// Displays the following:
// LINES NOT ENDING
//
// apple starts line one
// line three has apple in it
// there are no fruits in line four
// line five has an apple in it
// apple starts line seven
// there are no fruits in line eight
Remove lines not containing a particular string of text.
The text to match for removal is passed in along with an optional case sensitivity option.
The matching is based on regular expressions, so you must escape any regular expression special characters when passing them in.
You can always make use of the RegExp.TA_escape()
function to do this.
Returns the resulting text.
the string when found in a line constitutes a match for keeping.
when true
(the default), text matches will be case sensitive, and when false
, the matches will be case insensitive.
// Example
let strLines = `apple starts line one
line two ends with apple
line three has apple in it
there are no fruits in line four
line five has an apple in it
line six ends with apple
apple starts line seven
there are no fruits in line eight`;
app.setClipboard("LINES NOT CONTAINING\n\n" + strLines.TA_removeLinesNotContaining("apple"));
// Displays the following:
// LINES NOT CONTAINING
//
// apple starts line one
// line two ends with apple
// line three has apple in it
// line five has an apple in it
// line six ends with apple
// apple starts line seven
Remove lines not ending with a particular string of text.
The text to match for keeping is passed in along with an optional case sensitivity option.
The matching is based on regular expressions, so you must escape any regular expression special characters when passing them in.
You can always make use of the RegExp.TA_escape()
function to do this.
Returns the resulting text.
the string when found at the end of a line constitutes a match for keeping.
when true
(the default), text matches will be case sensitive, and when false
, the matches will be case insensitive.
// Example
let strLines = `apple starts line one
line two ends with apple
line three has apple in it
there are no fruits in line four
line five has an apple in it
line six ends with apple
apple starts line seven
there are no fruits in line eight`;
app.setClipboard("LINES ENDING\n\n" + strLines.TA_removeLinesNotEnding("apple"));
// Displays the following:
// LINES ENDING
//
// line two ends with apple
// line six ends with apple
//
Note the blank line at the end is simply because line 6 includes a newline character at the end
Remove lines not starting with a particular string of text. The text to match for keeping is passed in along with an optional case sensitivity option. Returns the resulting text.
the string when found at the start of a line constitutes a match for keeping.
when true
(the default), text matches will be case sensitive, and when false
, the matches will be case insensitive.
// Example
let strLines = `apple starts line one
line two ends with apple
line three has apple in it
there are no fruits in line four
line five has an apple in it
line six ends with apple
apple starts line seven
there are no fruits in line eight`;
app.setClipboard("LINES STARTING\n\n" + strLines.TA_removeLinesNotStarting("apple"));
// Displays the following:
// LINES STARTING
//
// apple starts line one
// apple starts line seven
//
Note the blank line at the end is simply because line 7 includes a newline character at the end
Remove lines starting with a particular string of text. The text to match for removal is passed in along with an optional case sensitivity option. Returns the resulting text.
the string when found at the start of a line constitutes a match for removal.
when true
(the default), text matches will be case sensitive, and when false
, the matches will be case insensitive.
// Example
let strLines = `apple starts line one
line two ends with apple
line three has apple in it
there are no fruits in line four
line five has an apple in it
line six ends with apple
apple starts line seven
there are no fruits in line eight`;
alert("LINES NOT STARTING\n\n" + strLines.TA_removeLinesStarting("apple"));
// Displays the following:
// LINES NOT STARTING
//
// line two ends with apple
// line three has apple in it
// there are no fruits in line four
// line five has an apple in it
// line six ends with apple
// there are no fruits in line eight
Removes any leading Markdown heading string from the start of a line in a string. Markdown expects a space to occur between the octothorpes and the title. This function also expects that. However, if there is a space at the start and no octothorpes, that space will be retaind - i.e. it matches on at least one octothorpe at the start. This is repeated for each line in the string. Returns the string with any leaading Markdown header removed.
// Example
alert(">" + "### Hello World".TA_removeMDHeader());
// Displays: >Hello World
Removes leading spaces and tabs from the lines of the string. Lines containing only spaces and tabs remain as empty lines. Initially empty lines remain unaffected. Returns the string stripped of such content.
// Example
strCleaned = strWithLeading.TA_removeSpaceTabLeading();
Removes leading and trailing spaces and tabs from the lines of the string. Lines containing only spaces and tabs remain as empty lines. Initially empty lines remain unaffected. Returns the string stripped of such content.
// Example
strCleaned = strWithLeadingAndTrailing.TA_removeSpaceTabLeadingTrailing();
Removes trailing spaces and tabs from the lines of the string. Lines containing only spaces and tabs remain as empty lines. Initially empty lines remain unaffected. Returns the string stripped of such content.
// Example
strCleaned = strWithTrailing.TA_removeSpaceTabTrailing();
Removes any number of new line characters from the end of the string.
```javascript // Example let strLines = ` foo bar
`; alert(">" + strLines.TA_removeTrailingNewlines() + "<"); // Displays the following: // > // foo // bar<
Removes leading whitespace from the lines of the string. Empty and lines only containing whitespace are removed. Returns the string stripped of such content.
// Example
strCleaned = strWithLeadingWhitespace.TA_removeWhitespaceLeading();
Removes leading and trailing whitespace from the lines of the string. Empty and lines only containing whitespace are removed. Returns the string stripped of such content.
// Example
strCleaned = strWithWhitespace.TA_removeWhitespaceLeadingTrailing();
Removes trailing whitespace from the lines of the string. Empty and lines only containing whitespace are removed. Returns the string stripped of such content.
// Example
strCleaned = strWithTrailingWhitespace.TA_removeWhitespaceTrailing();
Replace all text matching keys with values from the object map passed in. This function takes each key from the passed in object, searches for it in the string, and then replaces each occurrence with the value of that key.
object with named properties (key:value) that define each piece of text to find and what to replace it with.
// Example
alert("I have a lot of foo, and with that foo I also have some bar.".TA_replaceAllMap({"foo" : "quz", "bar" : "qux"}));
// Displays "I have a lot of quz, and with that quz I also have some qux."
Convert a string using the ROT13 self-reversible substitution cipher.
// Example
alert("hello world".TA_rot13();
If a string starts with a specific sub string, this returns the string with that part removed. The original string is otherwise returned unchanged.
the sub string to remove from the start of the string if it matches.
// Example
alert(`abcd`.TA_startsWithRemove("ab");
// Displays: cd
Strip any trailing new line from the string. The resulting string is returned.
// Example
let strURL = "foo\nbar\n";
alert(strURL.TA_stripFinalNewLine());
//Displays "foo\nbar"
Switch word markers.
This function is effectively designed around allowing quotation marks or other word boundary markers or separators to be switched from one form
to another. This can be used for example to switch smart quote characters to dumb quotes. To switch hyphens to en-dashes, etc.
The parameters are defined such that the first three and the second three define markers in the order before, in, and after a word.
Internally the function uses regular expressions to determine suitable matches, and if any initial parameter is a null string, no replacement
will be attempted for that marker. Note also that the marker will only be replaced if it is in the correct location. For example replacing a dumb
single quote ('
) as a pre-word marker will not replace such a character if it appears in or at the end of a word. Only when it appears at the start
or a word.
The function returns the update string.
a pre-word marker to be changed from.
a in-word marker to be changed from.
a post-word marker to be changed from.
a pre-word marker to be changed to.
a in-word marker to be changed to.
a post-word marker to be changed to.
// Example
alert`"No" said the man, "that's not it"`.TA_switchWordMarkers(`"`,`'`, `"`, `“`, `’`, `”`));
Returns second and subsequent characters of the string.
// Example
alert("foo bar".TA_tail());
// Displays "oo bar"
Modifies whether a string is a Taskpaper project or not.
Taskpaper projects end with a colon, so at a basic level the function is checking for a colon at the end, and
then adding or removing one as necessary to toggle if the string is a project or not.
It is effectively processing the last line of any string it is passed.
However, the two parameters provide overrides.
If both parameters are false
, the project status will be a simple toggle on/off.
If the parameters are true
and false
respectively, it will always be returned as a project.
If the parameters are false
and true
respectively, it will never be returned as a project.
If the parameters are true
and true
, the original string is returned.
when set to true
, the function always modifies to set the string to a Taskpaper project.
when set to true
, the function always modifies to set the string to not be a Taskpaper project.
// Example
alert("Project 1\nProject2:".TA_taskpaperModifyProject(false, false));
Modifies whether a string is a Taskpaper task or not.
Taskpaper tasks start with a hyphen and space (with any amount of whitespace preceding it).
At a basic level the function is checking for optional whitespace, a hyphen and space at the start, and
then inserting or removing one as necessary to toggle if the string is a task or not.
It is effectively processing the first line of any string it is passed.
However, the two parameters provide overrides.
If both parameters are false
, the task status will be a simple toggle on/off.
If the parameters are true
and false
respectively, it will always be returned as a task.
If the parameters are false
and true
respectively, it will never be returned as a tasl.
If the parameters are true
and true
, the original string is returned.
when set to true
, the function always modifies to set the string to a Taskpaper task.
when set to true
, the function always modifies to set the string to not be a Taskpaper task.
// Example
alert("- Task 1\n Task 2".TA_taskpaperModifyTask(false, false));
Normalises (NFC mode) and convert the string to Camel case. Camel case capitalises each word (others being lower cased) other than the first, which is all lower case, and removes spaces
// Example
alert("FOO bAr".TA_toCamelCase());
// Displays "fooBar"
Normalises (NFC mode) and convert the string to Kebab case. Kebab case lower cases each character and substitutes hyphens for spaces
// Example
alert("FOO bAr".TA_toKebabCase());
// Displays "foo-bar"
Normalises (NFC mode) and lower cases the string.
// Example
alert("Foo Bar".TA_toLowerCase());
// Displays "foo bar"
Normalises (NFC mode) and convert the string to Pascal case. Pascal case capitalises each word (others being lower cased), and removes spaces
// Example
alert("foo bAr".TA_toPascalCase());
// Displays "FooBar"
Normalises (NFC mode) and convert the string to Screaming Snake case. Screaming snake case upper cases each character and substitutes underscores for spaces
// Example
alert("FOO bAr".TA_toSnakeCase());
// Displays "FOO_BAR"
Normalises (NFC mode) and convert the string to sentence case.
// Example
alert("foo Bar".TA_toSentenceCase());
// Displays "Foo bar"
Normalises (NFC mode) and convert the string to Snake case. Snake case lower cases each character and substitutes underscores for spaces
// Example
alert("FOO bAr".TA_toSnakeCase());
// Displays "foo_bar"
Normalises (NFC mode) and converts a string to title case Please notes that this function is a slightly modified version of To Title Case 2.1
// Example
alert("foobar the QUZ qux".TA_toTitleCase());
// Displays "Foobar the QUZ Qux"
Related Copyright Information
To Title Case 2.1 – http://individed.com/code/to-title-case/
Copyright © 2008–2013 David Gouch. Licensed under the MIT License.
Normalises (NFC mode) and convert the string to Train case. Train case upper cases each character and substitutes hyphens for spaces
// Example
alert("FOO bAr".TA_toTrainCase());
// Displays "FOO-BAR"
Normalises (NFC mode) and upper cases the string.
// Example
alert("Foo Bar".TA_toUpperCase());
// Displays "FOO BAR"
Returns up to a fixed length of the string, and if the string exceeds, last character will be an ellipsis.
the maximum length of the string to be returned.
// Example
let strTest = `123456789①123456789②123456789③`;
alert(strTest.TA_trimToSnippet(23));
// Displays: 123456789①123456789②12…
Extract Drafts wiki-link content from a string. Paramters allow the links to be sorted alphabetically and deduplicated. Returns an array of all matching content (with the square brackets removed).
defaults to false
, but when set to true
, will alphabetically sort the array of links returned.
defaults to false
, but when set to true
, will ensure uniqueness of links in the array of links returned.
// Example
editor.getSelectedText().TA_wikiLinkContent(false, true);
Prefix and suffix each word in a string with strings of text.
the text to prefix each word with.
the text to suffix each word with.
// Example
alert("one, two, and three.".TA_wrapWords("<", ">"));
//Displays "<one>, <two>, <and> <three>."
String (Native)
The ThoughtAsylum library includes a set of extensions to the standard String object. These are used to simpify common actions in terms of interrogating and updating strings.