String Operations

JS
S
JavaScript

Best way of performing a cast to String without worrying about Type Errors or weird behaviours. Always use: String(typeToCast) Great tutorial: https://www.digitalocean.com/community/tutorials/how-to-index-split-and-manipulate-strings-in-javascript

1// Remove white spaces
2const withoutSpaces = value.replace(/\s/g, '');
3
4// Remove last character in the end of a string
5var str = 'Dr.'.replace(/.\s*$/, "");
6
7// Split by the n character
8const parts = value.match(/.{1,3}/g);
9
10// Find character codes
11"ABC".charCodeAt(0) // returns 65
12
13// Explicit Casting
14const numberToString = String(111);
15console.log(numberToString)
16
17// Abnormal Situations
18const nullToString = String(null);
19console.log(nullToString)
20// null.toString(); // !! Type Error !!
21
22// With Symbols
23var symbol = Symbol();
24String(symbol);
25
26// Replace all (/.../g) leading slash (^\/) or (|) trailing slash (\/$) with an empty string
27return myStr.replace(/^\/|\/$/g, '');
28
29// Replace character
30const mystring = "this,is,a,test"
31mystring.replace(/,/g , "newchar");
32
33//Remove Whitespaces
34const str = ' I have whitespaces ';
35const trimmedStr = str.trim();
36
37// Convert to LowerCase
38// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLocaleLowerCase
39const str = 'ALPHABET';
40const lowerCaseStr = str.toLocaleLowerCase(); // 'alphabet'
41
42// Sting contains a char
43if (str.indexOf('-') > -1){
44     // it has an '-'
45} else {
46    // it doesn't have
47}
48
49

Created on 12/6/2017