JavaScript String & RegExp - Yash-777/SeleniumDriverAutomation GitHub Wiki

Trim - Removing Leading and Trailing White Spaces & Replacing spaces with single spaces.

Removing and Replacing Spaces with some Character by using RegExp. [samples Left:{/^[\s]+/g} Right:{/\s+$/g} Trim:{/^\s+|\s+$/g} - use {\. , \|} instead of {. , |} directly as a RegExp]

The RegExp constructor creates a regular expression object for matching text with a pattern.

Syntax

Literal and constructor notations are possible:

/pattern/flags
new RegExp(pattern[, flags])

new RegExp('ab+c', 'i');
new RegExp(/ab+c/, 'i');

flags If specified, flags can have any combination of the following values:

g « global match; find all matches rather than stopping after the first match
i « ignore case
m « multiline; treat beginning and end characters (^ and $) as working over multiple lines (i.e., match the beginning or end of each line (delimited by \n or \r), not only the very beginning or end of the whole input string)
u « unicode; treat pattern as a sequence of Unicode code points
y « sticky; matches only from the index indicated by the last Index property of this regular expression in the target string (and does not attempt to match from any later indexes).

Example Code Snippet:

var trim = str.replace(/^\s+|\s+$/g, '')

var str = ' \r \t \n Remove \n leading and \t trailing white spaces \r \t \n ';
String.prototype.singleSpace = function( ) {
    return this.replace( new RegExp(/^[\s]+$/, 'gm'), '' ).replace( new RegExp('\\s+', 'gm'), ' ' );
}
console.log('Single Space B/W Words :'+str.singleSpace().toUpperCase()+"~" );

String.prototype.trimLR = function () {  
    return this.replace(/^\s+|\s+$/g,'');  
};  


console.log("Trim:"+str.trim());
console.log("TrimLR:"+str.trimLR());
/*O/P:
 Trim:Remove 
 leading and 	 trailing white spaces 

 TrimLR:Remove 
 leading and 	 trailing white spaces*/

Reserved characters in HTML must be replaced with character entities. [&, &amp]

Character entity references in HTML: Test the below code snippet on this Application URL:

var element = document.evaluate('//table[@class="w3-table-all notranslate"]/tbody/tr[5]/td', window.document, null, 9, null ).singleNodeValue;
console.log('HTML:', element.innerHTML);
var JS = (element.innerHTML).replace('&', '&');
console.log(JS);

Regex quick reference

[abc] A single character of: a, b, or c . Any single character (...) Capture everything enclosed
[^abc] Any single character except: a, b, or c \s Any whitespace character (a\b) a or b
[a-z] Any single character in the range a-z \d Any digit a? Zero or one of a
[a-zA-Z] Any single character in the range a-z or A-Z \D Any non-digit a* Zero or more of a
^ Start of line \w Any word character (letter, number, underscore) a+ One or more of a
$ End of line \W Any non-word character a{3} Exactly 3 of a
\A Start of string \b Any word boundary a{3,} 3 or more of a
\z End of string a{3,6} Between 3 and 6 of a