Tinderbox v10 Icon

String.replace(regexMatchStr, replacementStr)


Operator Type: 

Operator Scope of Action: 

Operator Purpose: 

Data Type Returned: 

Operator First Added: 

Operator in Current Baseline: 

Operator Last Altered: 

Operator Uses Regular Expressions: 

 Function  [other Function type actions]

 Item  [operators of similar scope]

 Data manipulation  [other Data manipulation operators]

 String [about String data type]

 v5.7.0

 Baseline

 As at baseline

 [More on regular expressions in Tinderbox]


String/List.replace(regexMatchStr, replacementStr)

This operator allows simple text transformations without use of runCommand as was hitherto required.

regexMatchStr and replacement are one of:

$MyString.replace(regexMatchStr, replacementStr)

In its simplest form, the operator creates a new string in which each occurrence of regex is replaced by the string replacement, i.e. global replacement. The source string is not changed by replace; if you wish to change the string itself, write back over the source attribute:

$MyString = $MyString.replace("Hello","Goodbye"); 

transforms a $MyString value of "Hello World" to "Goodbye World".

Where regexMatchStr is a regular expression, and may contain wildcard characters such as "." (which matches any character) or "*" (which matches 0 or more occurrences of the preceding character). Thus ".*" matches zero or more instances of any character.

Where parentheses in regexMatchStr create multiple back-references, replacementStr strings can include $1, $2, etc., to insert the relevant back-reference matched string ($1 through $9 allowed, and with $0 being the entire match).

The replacement replacementStr preserves styles in the source String.

Examples:

$MyString.replace("Spenser","Spencer"); 

changes all instance of "Spenser" to "Spencer".

$MyString.replace("(a|e|i|o|u)",""); 

deletes all vowels

$MyString = "I do not like green eggs".replace("(green) (eggs)","$2 $1"); 

returns "I do not like eggs green". Or:

$Text=$Text.replace("From: (.+)@(.*)","——$1——\n$2"); 

Will replace

From: mark@example.com 

with

	——mark——
	example.com

Note that if the source text is part of a larger text, e.g. a whole email's plain text, consider using stream parsing methods.

A replace action does not alter the original source

Using .replace() does not affect the source string unless the replacement output is used to overwrite the original source value. Thus if $MyString holds "Hello World" then:

$MyStringA = $MyString.replace(" World"); 

$MyString remains "Hello Word" and $MyStringA has value "Hello". The source is unchanged. But, if we set the source to the output

$MyString = $MyString.replace(" World"); 

Now $MyString becomes "Hello" and the original value is lost (overwritten by the new one). This distinction is one to bear in mind when using .replace() with $Text.

Using .replace() with $Text and formatting operators

When applied to $Text, .replace() allows style operators to be applied to the replacement argument. For example,

replace("^ from: .*",$0.bold) 

will embolden all lines beginning with “From:”.

If using style operators, do not place operator-modified back-reference within quotes. To re-use the example from above, consider $Text containing "I do not like green eggs and ham":

$Text = "$Text.replace("(green) (eggs)",$2.bold+" "+ $1.strike); 

gives "I do not like eggs green and ham".

Multiple, but differing replacements

Although multiple matches can be replaced with the same string, to replace multiple matches with different strings requires chained .replace() calls. Consider formatting a large number to Continental style. This means inserting spaces as the group delimiter and a comma for the decimal delimiter. Assume $MyNumber's value is 1234567.89:

$MyString = $MyNumber.replace("(\d)(?=(?:\d{3})+([^\d]))","$1 ").replace("\.",","); 

Now, 1234567.89 becomes "1 234 567,89".

Some comma-delimited formats use straight double quotes for all/some values and demand that if this character appears in a value that is it escaped by doubling the character. If $Text is

He shouted "Hello!" at the top of his voice. 

Then it could be escaped for CSV export like so:

…,"^value($Text.replace('"','""'))^",… 

That exports:

…,"He shouted ""Hello!"" at the top of his voice.",… 

Note that in this instance using a single straight quote (instead of the more normal straight double quote) to contain the find and replace regexs works just fine. Also, there is no need to escape typographic double quotes, i.e. 'smart' or 'curly' quotes in this context.

This function respects existing rich text styling.

Short form for deletions

If the replacement string is omitted, the one-argument form $MyString.replace(regex) returns a copy of $MyString in which every occurrence of the regex is removed.

Trimming leading/trailing whitespace

$MyString = $MyString.replace("^ +","").replace(" +$",""); 

The ' +' means one or more space characters. The first replace finds such a sub-string immediately following the start of the whole string ^), whilst the second does the same for a sub-string immediately before the end of the string ($). If applied to multi-paragraph string, e.g. with line breaks such as in $Text, every paragraph is trimmed. Likely this is what is desired, but care is needed in more specialist situations. So, testing sample strings/texts is a good idea before changing actual data of value. If working with List or Sets a slightly different code is needed.

Trimming leading/trailing quotes

Because Tinderbox cannot escape quote characters (i.e. \" or \' do not escape the quote), use String.substr() to trim enclosing quotes on a string. Note that the latter, working on location in the string and not character type, cannot work on paragraphs within a string, such as in the example above.

Dealing with inline quote characters

Because regex is parsed for regular expressions, it may be possible to use the '\xNN' form of character encoding described here to work around the lack of escaping from single double quotes within strings.

Handling changes to $Text including link anchors

When using .replace is used on a note's $Text, the replaced text also updates the position of pre-existing text link anchor text.

Working with styled text

This operator is capable of worthing with StyledString operators: StyledString.bold, StyledString.fontSize(), StyledString.italic and StyledString.strike.


See also—notes linking to here: