string method in javascript code example
Example 1: is string javascript
function isString(value) {
return typeof value === 'string' || value instanceof String;
}
isString('');
isString(1);
isString({});
isString([]);
isString(new String('teste'))
Example 2: js string methods
JS String Methods:
charAt()
Returns a character at a specified position inside a string
charCodeAt()
Gives you the unicode of character at that position
concat()
Concatenates (joins) two or more strings into one
fromCharCode()
Returns a string created from the specified sequence of UTF-16 code units
indexOf()
Provides the position of the first occurrence of a specified text within a string
lastIndexOf()
Same as indexOf() but with the last occurrence, searching backwards
match()
Retrieves the matches of a string against a search pattern
replace()
Find and replace specific text in a string
search()
Executes a search for a matching text and returns its position
slice()
Extracts a section of a string and returns it as a new string
split()
Splits a string object into an array of strings at a specified position
substr()
Similar to slice() but extracts a substring depended on a specified number of characters
substring()
Also similar to slice() but can’t accept negative indices
toLowerCase()
Convert strings to lowercase
toUpperCase()
Convert strings to uppercase
valueOf()
Returns the primitive value (that has no properties or methods) of a string object
Example 3: js string
let longString = "This is a very long string which needs " +
"to wrap across multiple lines because " +
"otherwise my code is unreadable.";
Example 4: js strings
let color = "purple";
let city = 'Tokyo';
city.length;
city[0];
city[3];
'hello'.toUpperCase();
'LOL'.toLowerCase();
' omg '.trim();
'spider'.indexOf('i');
'vesuvius'.indexOf('u');
'cactus'.indexOf('z');
"pancake".slice(3);
"pancake".slice(0, 3);
"pump".replace("p", "b");
const color = "olive green";
const msg = `My favorite color is: ${color}`
const str = `There are ${60 * 60 * 24} seconds in a day`
Example 5: js string methods
'hello'.toUpperCase();
'LOL'.toLowerCase();
' omg '.trim();
'spider'.indexOf('i');
'vesuvius'.indexOf('u');
'cactus'.indexOf('z');
"pancake".slice(3);
"pancake".slice(0, 3);
"pump".replace("p", "b");