A series of methods for the javaScript String Object, all methods have names starting wider_
- This provides a collection of methods that extend the javascript String object to allow simpler and easier to read code. Elsewhere many javascript string processing function are declared as stand alone procedures and not as properties if the String object and may have different code implementations in different environments/version or not available in all environments.
For example in older implementations of javascript escape() would give different results in different environments / versions and is not even available in later versions
When used in multiple combinations as prefix function calls, the standard javascript code is needlessly inelegant and harder to maintain - either requiring numerous separate statements or nested method calls which are hard to read amd have a risk of misplaced parentheses or even parameters.
With these methods in this module you can blend native postfix method calls as well as these custom methods with code that is easy to read.
The exported object of this module is an object to be assigned to your String class or your extension thereof. The methods assigned to the class are the methods of this module which have parentheses appended to their method name. To avoid current or future risk of name conflict, all names are prefixed with .wider_ when used - for example
"myString".wider_camelIse()
- Copyright:
- Copyright (C) 1985..2021 Martin Baker. http://y-d-r.co.uk
- License:
- ISC Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
Methods
-
inner asHTML()(outerElementopt, modeopt) → {string}
-
Ensure that the given text is in HTML format, changing it is necessary
Parameters:
Name Type Attributes Default Description outerElementobjectname <optional>
'div' optional tag name of the outer element - ignored if the text contains newline characters. Defaults to
divorspanaccording to the presence of newlines. Also ignored if the text also appears to be HTML.modeenum <optional>
values |strict|markdown|
strictthe content must be strict xml and will be coerced to be so if it isn't.markdownif the text is not HTML then it is treated as a markdown document (if it starts with a single # heading or markdown fragment otherwise)Returns:
string -If already appears to be HTML then returns the original text If it contains one one more lines then return one of more elements (for \n\n) and
for (\n). If a line starts with a markup cann generateh1etc or <code<li` markups. if there are no newlines then HTML as an inline block </">Useful for including thrown error messages into an HTML response Please refer to the documentation in ydr/data/resources to see the markups this generatesExample
"*head=1: my title\nhere is a line\n\n* here is a \"bullet\"\n*and <another?".wider_asHTML() // ... "<div><h1> my title </h1> here is a line <p class="bullet"> here is a "bullet" <p class="bullet">and <another? </div>" "line1\nline2\nline3".wider_asHTML("span") // "<span>line1<br/>line2<br/>line3</span>" -
inner attrEncode()() → {string}
-
Encode a string so it may appear in the text of an HTML or XML attribute for an element you are preparing in plain text We assume you will placing the result in a string delimited by quotation marks and not apostrophes
Returns:
string -string with any characters that would conflict with XML syntax encoded to be safe
Example
> "sfgsdf< \n sdfgsdg \"".wider_attrEncode() // "sfgsdf< 
 sdfgsdg "" -
inner camelIse()() → {string}
-
Turns any string into a camelised identifier - action is mostly reversed by
.deCamelIse().In order to be reversible the camelisation process is slightly different to the norm when dealing with the transition between an acronym and a following name. So an XML string becomes anXMLstring and hence
const demo = "an XML string"; demo.wider_camelIse().deCamelIse() == demo; // trueBUT if the string starts with a hard space the first hard space is removed and the string left otherwise unchanged.
Note the camelisation of this function's name
.wider_camelIse()and.wider_deCamelIse()are often used with enumerated lists enabling a data value to have the form of an objectname convenient for data use and to generate a neat alternative for the user to read and writeReturns:
stringExample
"hold my hands up".camelIse() // holdMyHandsUp "HTML encode".camelIse() // HTMLencode -
inner checkSum()(modeopt) → {string}
-
Generates a mod 97 checksum and appends it to the string. The string may contain formatting; any non digit character is excluded from the computation Further checksum formats will be added according to pressures to include them
Parameters:
Name Type Attributes Default Description modeenum <optional>
numeric97 the type of checksum required
- numeric97 = mod 97 all non digits are ignored - multiply the numeric value of each digit by its character position in [3,5,7,11,13,17,19,23,29,31] rotating so
9876
becomes
` (9*3 + 8*5 + 7*7 + 6*11 ) mod 97 = 85`
Returns:
string -the original value augmented by its checksum
Example
"aasdf".wider_checksum() // "aasdf00" "123456789123456789123456789123456789".wider_checkSum() // "12345678912345678912345678912345678904" "GB 1245/6789-".wider_checkSum() // "GB 1245/6789-78" - numeric97 = mod 97 all non digits are ignored - multiply the numeric value of each digit by its character position in [3,5,7,11,13,17,19,23,29,31] rotating so
9876
becomes
-
inner checkSumValidate()(mode) → {boolean}
-
Generates a mod 97 checksum and appends it to the string. The string may contain formatting; any non digit character is excluded from the computation
Parameters:
Name Type Description modeenum the mode that the checksum would have been created in by
.checkSum()Returns:
boolean -true if the checksum is valid as the last two characters of the string
Example
"aAsdf00".checkSumValidate() // true "123456789123456789123456789123456789".checkSum() // "12345678912345678912345678912345678904" "GB 1245/6789-".checkSum() // "GB 1245/6789-78" -
inner contextParse()()
-
Takes a context string and converts it into an object.This object may later be extended by the
$wider.datato facilitate data updates or deletes or to create new rowsExample
"FINANCE:transactrowsRowId_4012:name:webfile".contextParse() // ... ContextParse { urn: "FINANCE", id: "transactrowsRowId_4012", target: "transactrowsRowId_4012", attribute: "name", xpath: "webfile", buttons: undefined, selector: undefined, action: undefined, context: "FINANCE:transactrowsRowId_4012:name:webfile" } -
inner deCamelIse()() → {string}
-
Turns any camelised string into a space separated string - action is mostly reversed by .camelIse
BUT if the string starts with a hard space the first hard space is removed and the string left otherwise unchanged.
Note the camelisation of the function name
.camelIse()>and.deCamelIse)are often used with enumerated lists enabling a data value to have the form of an objectname and to generate a neat alternative for the user and to work back from what the user enters to the objectnameReturns:
stringExample
"aasdf".deCamelIse() // aasdj "holdMyHandsUp".deCamelIse() // "hold my hands up" "HTMLencode".deCamelIse().camelIse() // "HTMLencode" "wasThatIBMsoftware".deCamelIse() // "was that IBM software" "HTMLEncode".deCamelIse() // "HTMLEncode" --- note shown to avoid inelegant forms "HTMLEncode".deCamelIse().camelIse() // "HTMLencode" -
inner ellipses()(widthMaxnullable, heightMaxopt, modeopt) → {string}
-
Limit the length of a string as sent fo HTML display. Sometimes you want only so much of a string - if it is short then fine, but if the string is too long you only want so much <p?String may be plain text or HTML
Parameters:
Name Type Attributes Description widthMaxpositiveInteger <nullable>
count of the ems width you want to allocate
heightMaxpositiveInteger <optional>
count of the ems height you wish to allocate
modeenumList <optional>
if present then a space delimited list
Returns:
string -HTML encoded string ellipsed if it is longer than space specified
Example
> "fdsgsdfgsdfg sdfg s sdfg sdfg sdfg sdfg sdf gb".ellipses(20) //"<span class="ellipses" style="white-space:nowrap; width:20em"><span>fdsgsdfgsdfg sdfg s sdfg sdfg sdfg sdfg sdf gb</span></span>" -
inner escape()() → {string}
-
Generates an old school equivalent of the escape () function found in many older browsers. Use this to avoid different behaviours according to the age of the javascript engine you are using
This roughly follows the ecma-262/5.1 https://www.ecma-international.org/ecma-262/5.1/#sec-15.1.3 within the limited context of the original early versions so it does not mess with any character above \x1F per the original form of the function Do not use this as a substitute for URI Handling Function Properties - this is for when you want to encode something that is not a URI so it doesn't conflict with other controlling characters you may use The result may be used directly in an HTML attribute without compromising attribute or tag delimiters and may be used in a formData string.
- ; \ / ? : @ & = + $ ecma-262/5.1/#sec-15.1.3 uriReserved
- % ecma-262/5.1/#sec-15.1.3 uriEscaped
- - _ . ! ~ * " () ecma-262/5.1/#sec-15.1.3 uriMark
- space # < > { } [ ] additions for backwards compatibility
Returns:
stringExample
"sdf : ; - + / \\ { } ".wider_escape() // "sdf%20%20%20%3a%20%20%20%3b%20%20%20%2d%20%20%2b%20%20%2f%20%20%20%20\\%20%20%20%7b%20%20%20%7d%20%20%20" -
inner extendedCharCodeFixer()() → {string}
-
When one creates an xml object and its output contains extended character codes these can get mapped onto character code with values in excess of 127. In older systems with code pages you can get character corruptions when using database, javascript and client side HTML rendering. This is particularly prevalent when people paste in content from older applications such as older versions of MS Word. This converts all unicode and extended character set copes above \x80 so that in effect you get UTF-7 rendering - which is carried safely in UTF-8 standard for javascript and various browser code pages
Throws:
-
if not part of a @wider/utils_bundle solution - so just dont use it
- Type
- Error
Returns:
string -HTML string compatible with the original but with extended characters
-
-
inner formStrToXMLattr()(modeopt) → {string}
-
Take a standard http request queryString (eg as in Request.queryString) or in formData and returns it as a string in the form of xml property name value pairs ready for insert in an xml element eg
field1="lkjj;l" field2="lklkklh"etc<.p> unless mode is withNulls, empty or missing attributes are not included in the xmlif the string has real unencoded newlines WITHIN an attribute value then these are JS escaped as is this is a formatting errorParameters:
Name Type Attributes Description modeenum <optional>
values |withNulls| if present then attributes given in the source that have no value are supplied as empty strings otherwise they are suppressed
Returns:
string -XML attribute list
Example
> "field0&field1=here%20is%20my%20contentm%5bin%20here%5d&field2=here%20is%20my%20content%20%3cin%20here%3e".formStrToXMLattr() // "field1="here is my contentm[in here]" field2="here is my content &lt;in here&gt;" " > "field0&field1=here%20is%20my%20contentm%5bin%20here%5d&field2=here%20is%20my%20content%20%3cin%20here%3e".formStrToXMLattr("withNulls") // "field0="" field1="here is my contentm[in here]" field2="here is my content &lt;in here&gt;" " -
inner fuzzyValue()(modeopt) → {string}
-
Generates an encoding of a word or phrase that can be used to search a list - useful for use entry on long pick lists allowing typos and spelling errors to handled
At the client, we suggest you use this method repeatedly with increasing rules until you get a short enough option list from your dataset
Parameters:
Name Type Attributes Default Description modeenumList <optional>
basic zero or more of the values |basic|harsh|noVowels|alpha|
- basic - in which all spaces are removed, chars converted to lowercase, and utf-8 extended characters either removed or converted to lowercase a-z equivalents other characters are generally preserved
- harsh - removes all duplicate adjacent letters
- noVowels - aeiouy like letters removed (but accented ones kept)
- alpha - // only a-z A-Z \xff
Returns:
string -} sting reduced for fuzzy comparison
Example
> "I have a sore Œsophagus".fuzzyValue() "ihaveasoreœsopegus" > "I have a sore Œsophagus".fuzzyValue("basic") "ihaveasoreœsopegus" > "I have a sore Œsophagus".fuzzyValue("harsh") "I have a sore sophegus" > "I have a sore Œsophagus".fuzzyValue("harsh noVowels") "I hv sr sphgs" > "I have a sore Œsophagus".fuzzyValue("basic harsh noVowels") "hvsrœspgs" > "I have 1 sore Œsophagus".fuzzyValue("alpha") "havesoresophegus" -
inner HTMLencode()(conditionopt, settingsopt) → {string}
-
Convert a string so that it is safe for use as text content in HTML. If the string is already HTML it will still be encoded - rendering the HTML markups visible to a user viewing the result.
See also
myString.wider_attrEncode()for strings that are safe to place inside an xml or HTML attribute See alsomyString.wider_asHTML()which only converts if the string is not already HTML.Parameters:
Name Type Attributes Description conditionenumList <optional>
values
'newlines'HTML'markdown- If this contains
HTMLthen if the string already appears to be HTML syntax then it is not amended - if this contains
newlinesthen new line markers are replace with their HTML character code equivalent - if this contains 'markdown' then markdown-it will be used if the string appears to be markdown. Your must call `"".wider_HTMLencode("markdownInit") ONCE in lifetime before calling with this option
- if this is ONLY 'markdownInit' then the markdown tool is loaded dynamically on its first use to prevent bloat if it is not used. So if you intend to use this feature then call
"".wider_HTMLencode("markdown", [settings])to initialise. The result will be a Promise that triggers when ready. In general, unless you are initialising just in time, you cam ignore the Promise if you execute this call immediately you have imported this module. See example in the test.js source code
settingsObject <optional>
if present then defines the custom settings for this call only
Returns:
string -the marked up string
- If this contains
-
inner HTMLencodeInit(settingsopt) → {Promise}
-
Initiates dynamic loading of the markdown utility within HTMLencode and sets its defaults - onluy does so if markdownIt is present in global.$wider
Parameters:
Name Type Attributes Description settingsObject <optional>
the markdown-it settings to be used
Throws:
-
if solution has not loaded markdown-it
- Type
- Error
Returns:
Promise -fires when ready - in most usages you do not need to wait on this Promise - see worked example
-
-
inner isHTML()() → {boolean}
-
performs a simple check to determine if the string looks like HTML
Returns:
boolean -true if the string looks like HTML
Example
"sdfdgs".wider_isHTML() // false "<div>sdfdgs</div>".wider_isHTML() // true -
inner isHTMLerror()() → {boolean}
-
Detects if the HTML message is wrapped with a class that contains one of the default error classes error userError developer or developerHide as potentially created by
.wider_wrapAsError(session)Returns:
boolean -true if the string is an error HTML at the outer node level of the content
Example
> "<span>Yippee</span>".wider_wrapAsOK("myFile.js", null, "doing and Example").wider_isHTMLerror() // false > "<span>Yippee</span>".wider_wrapAsError("myFile.js", null, "doing and Example").wider_isHTMLerror() // true -
inner proper()(modeopt) → {String}
-
Capitalises first characters of selected words according to the given mode.
Deals with extended latin alphabet up to
\xff. Not certified for other characters beyond\xffParameters:
Name Type Attributes Description modeenum <optional>
If omitted the the first character of the first word is capitalised
if ** * throughout*** then capitalises first character of every word
if intelligent then capitalises first character of every word excluding words not normally capitalised in paragraph headings - see code for list of affected words
Returns:
String -the capitalised string
Example
// using a rare old English version of modern (English) oesophagus or esophagus (AMERICAN) to illustrate œsophagus "i have a sore œsophagus".proper() //"I have a sore Œsophegus" "i have a sore œsophagus".proper("throughout") //"I Have A sore Œsophagus" "i have a sore œsophagus".proper("intelligent") //"I have a sore Œsophagus" -
inner regExpEncode()() → {string}
-
Encodes string so that it can be placed in a regular expression to be searched for so deals with characters that conflict with regExpr commands
Returns:
string -the given string adapted so it can be used in new RexExp()
Example
> "look for a variable called "".wider_searchEncode() // "look for a variable called \\$wider" -
inner replaceSafe()() → {string}
-
Amends the parameters to the standard javascript
.replace()so that the characters normally interpreted in the newValue as replacement instructions are left as they are if you need the same protection on the pattern then apply.searchEncode()to the pattern as you create a regEpr for it or just pass into this function in one stepReturns:
string -the string replaced as expected
Example
const demo ="my this is $ a (weird) a-z string"; demo.replaceSafe("$ a (weird) a-z".searchEncode(), "a $1 crazy") // "my this is a $1 crazy string" -
inner searchEncode()()
-
Encodes string so that it can be placed in a regular expression to be searched for so deals with characters that conflict with regExpr commands
- Deprecated:
- use wider_regExpEncode
-
inner selectorEncode()() → {string}
-
Returns:
string- Deprecated:
- Yes
-
inner simpleHTMLtoPlain()() → {string}
-
Returns:
string -a plain text string in notepad like plain text format
-
inner standardMarkups()() → {boolean}
-
implements a standard set of macro expansions across both clientside and serverside strings
see settings of m_markupMap below for supplementary marks ups according to location
Returns:
boolean- Deprecated:
- Yes
-
inner stringEncode()(modeopt) → {string}
-
Encodes a string so it can be placed in context where real new lines are not permitted - as in the creation of dynamic javascript ready to be submitted to
eval().Parameters:
Name Type Attributes Description modeenum <optional>
values |jsStrict| if present this is for use when creating an javascript expression to be submitted to
eval(). This handles newlines which are not generally permitted within scripts.Use without this parameter if you wish to write the result to a file
Returns:
string -the given string adapted so it can be used in a file or javascript expression
-
inner textSignature ()() → {number}
-
Generates a one way cypher for a string - you cannot decrypt this back to the original string
Originally written in 1986 in visual basic and converted to javascript - it is impossible to bust. Safe to use on unencrypted transfer between client and server although generally nowadays this is not recommended
Used for passing passwords around such that you never need to send the original password from the work station. Hence the real password can never be hacked at the server, cannot appear in any log file, and there is no way for even the original developer to reverse engineer what the password was. Those out there doing statistics on passwords will never be able to find out what passwords are being used - that they can do so under normal solutions shows their security exposures.
Can also be used as a signature for the state of some data - send this to the client and if they cannot send a match back to the data with a proposed update (eg because the original has changed) you can initiate a failure because your optimistic locking process failed - or because there has been some hacking
Returns:
number -A number to use as signature - see $wider.logon for an example of secure password transfer and $wider.data for use for data optimistic locking process
-
inner trim()(modeopt) → {string}
-
Remove leading and trailing whitespace from the string, optionally collapsing multiple whitespace to a single space
Parameters:
Name Type Attributes Description modeenum <optional>
values |neat| additionally collapse multile whitespace within a string to single spaces
Returns:
string -string pruned of unwanted whitespace
Example
> " sfdg sdfgds sfbg s ".trim("neat") // "sfdg sdfgds sfbg s" -
inner unescape()() → {string}
-
Generates an old school equivalent of the unescape () function found in many older browsers
The escape function generates a string that can be unescape by the modern
decodeURIComponent()Returns:
stringExample
"sdf%20%20%20%3a%20%20%20%3b%20%20%20%2d%20%20%2b%20%20%2f%20%20%20%20\\%20%20%20%7b%20%20%20%7d%20%20%20" .unescape() // "sdf : ; - + / \\ { } " -
inner unHTMLencode()() → {string}
-
Undoes the effect of wider_HTMLEncode - returning a plain javascript string
This will only undo what wider_HTMLEncode() does plus and numerical encodings, eg - it does not convert named encodings UNLESS you or another package such as @wider/core_data separately has a dependency on it. If that is missing then this simply skips the named items except for the HTML core items < etc
if your string already has real HTML characters in it, then you will not be able to tell the difference between the original HTML characters and the ones this has just created, You cannot presume that the output string is HTML/XML unless you know it was created originally by
wider_HTMLencode()or an equivalentReturns:
string -
inner wrapAsError()(issueropt, divClassopt, titleopt, nestingopt)
-
Wrap HTML in a
divelement with standard YDR attributes to indicate that the content is considered to be the result of an unsuccessful action by the application or because of a user or client side error. Also to label it should the developer need to track down its source for forensic purposes While all params are optional it is recommended that at least issuer and title are providedParameters:
Name Type Attributes Default Description issuersiteUrl <optional>
a url and or an object/method name that the developer will recognise as identifying the code 5that issued this fragment of an HTML response or content that is filed in a database
divClassobjectnameList <optional>
error values to be set as the @class attribute if required otherwise defaults to "error". When running in the YDR Framework these values can lead to automatic actions at the client - eg to revert to the previous data entry form for its correction and resubmission
titleinlineHTML | plainText <optional>
If this fragment becomes the outer fragment of a server response then this will be the title of the page or the dialog
nestingenum <optional>
values !neverNest| if present then directs that the recipient client software of the message should not show this error message as a child error message of an earlier version of itself. If there is a fault situation that can lead to circular issues of this fault message then the circle is required to be broken by action at the client (eg as implemented in the YDR clientside framework)
Example
> "Error: XMLverify is only available within ydr Framework".wider_wrapAsError("myFile.js", null, "doing and Example") // "<div class="error" data-ydr-action="error" data-ydr-issuer="myFile.js" data-ydr-title="doing and Example" data-ydr-widthideal="40"> Error: XMLverify is only available within ydrFramework</div>" -
inner wrapAsOK()(issueropt, divClassopt, titleopt)
-
Wrap HTML in a
divelement with standard YDR attributes to indicate that the content is considered to be the result of a successful action by the application. Also to label it should the developer need to track down its source for forensic purposes While all params are optional it is recommended that at least issuer and title are providedParameters:
Name Type Attributes Default Description issuersiteUrl <optional>
a url and or an object/method name that the developer will recognise as identifying the code that issued this fragment of an HTML response or content that is filed in a database
divClassobjectnameList <optional>
OK values to be set as the @class attribute if required otherwise defaults to "OK". When running in the YDRframework these values can lead to automatic actions at the client - eg to terminate the requesting dialog because it was successful and revert to that dialog"s parent if any. Actions are determined by your client system or by the YDR clientside framework if you are using it
titleinlineHTML | plainText <optional>
If this fragment becomes the outer fragment of a server response then this will be the title of the page or the dialog
Example
> "<span>Yippee</span>".wider_wrapAsOK("myFile.js", null, "doing and Example") "<div class="OK" data-ydr-action="OK" data-ydr-issuer="myFile.js" data-ydr-title="doing and Example"><span>Yippee</span></div>" -
inner XMLverify()(actionopt) → {string}
-
Given any string - validates if it is usable as a string for XML purposes namely that it is can be loaded as an single but possibly deep xml element or that it is not an XML string at all.
HTML formally constructed compliant to XML standards will be accepted
Note for comparison that
.wider_isHTML()only checks that a string looks like XML/HTML, but it could be a list of several XML elements and could have not XML components eg Only usable when running under the YDR frameworkParameters:
Name Type Attributes Default Description actionenumList <optional>
throw values |fix|throw|fragment|required| controls as to what should occur, pick as many as required in any order
- fix - if the string does not look like XML it is HTML encoded in strict XML format
- throw - if the string does not look like XML throw an error
- fragment - the string may represent multiple top level XML elements otherwise fix or throw
- required - the input string must be XML - a plain text non XML string will be rejected
Throws:
-
if not part of a @wider/utils_bundle solution - so just dont use it otherwise
- Type
- Error
Returns:
string -string pruned of unwanted whitespace
Example
> "zbcvbxcvb".XMLverify() Thrown: Error: XMLverify is only available within ydrFramework