Text
Case
> myText.toUpperCase()
Slicing
myText.substr(first, length)
myText.substring(start, end)
myText.slice(start, end)
For using .substr
or .slice
, see SO thread.
e.g.
> 'abcd'.substr(0,2)
'ab'
> 'abcdef'.substring()
'abcdef'
> 'abcdef'.substring(0)
'abcdef'
> 'abcdef'.substring(1)
'bcdef'
> 'abcdef'.substring(1,3)
'bc'
> 'abcdef'.substring(0,3)
'abc'
>
> 'abcdef'.slice(1,3)
'bc'
Replace text in text
Replace first occurence only
Replace the first occurence, not a global replace.
Pass first param as a string, not regex.
> 'AAA'.replace('A', 'C')
'CAA'
Or pass regex, but without g
:
> 'AAA'.replace(/A/, 'C')
'CAA'
Replace all occurences
A newer method added to JS:
> 'AAA'.replaceAll('A', 'C')
'CCC'
Using regex - note g
for global replace.
> 'AAA'.replace(/A/g, 'C')
'CCC'
Or the more verbose:
> 'AAA'.replace(new RegExp("A", "g"), 'C')
'CCC'
You might use RegExp
to escape characters for you.
> new RegExp("A", "g")
/A/g
> new RegExp("/A")
/\/A/
Remove empty lines
> myText.replace(/^\n/gm, '');
The Regex pattern finds lines which start with a newline.
The m
modified is recommended for multi-line search
If you wanted to just replace a value, you could do:
> myText.replace(/^$/g, 'new value');
Remove whitespace at start and end
- trim method in MDN docs
The
trim()
method removes whitespace from both ends of a string. Whitespace in this context is all the whitespace characters (space, tab, no-break space, etc.) and all the line terminator characters (LF, CR, etc.).
myText.trim();
e.g.
> ' foo '.trim()
'foo'
Remove only newlines from start and end
> myText.replace(/^\n|\n$/g, '');
Note this removes all whitespace and not just \n
.
Template literals
See Template literals on Mozilla docs.
Split
Split by delimeter
'abc def ghi'.split(' ')
// [ 'abc', 'def', 'ghi' ]
String to array of characters
'abcdef'.split('')
// [ 'a', 'b', 'c', 'd', 'e', 'f' ]