Knowing string functions is always useful and saves time to Google the correct function. Hence I have prepared list of most useful, usually used string functions.
First of all definition of String
In computer programming, a string is traditionally a sequence of characters, either as a literal constant or as some kind of variable.
In JavaScript context it inherits prototype of String object.
A string can be any text inside double or single quotes.
List of almost all kinds of string manipulations.
Creating a String:
var name = new String (“sachin”)
Or simply
var name = “sachin”
Changing a String
Replace
name.replace(“in”,”out”)
replace replaces first occurrence only.
Change case
name.toUpperCase()
name.toLowerCase()
// Custom title case function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var titleCase = function(sent){ | |
var sentArr = sent.split(" "); | |
var titleCaseArr = []; | |
for(i=0;i<sentArr.length;i++) | |
{ | |
sentArr[i]=sentArr[i].trim().charAt(0).toUpperCase() | |
+sentArr[i].substring(1,sentArr[i].length); | |
if( sentArr[i].trim().length>0 ) | |
{ | |
titleCaseArr.push(sentArr[i].trim()); | |
} | |
} | |
return titleCaseArr.join(" ") | |
} | |
console.log(titleCase("India is my country")) // India Is My Country |
Concat
var fullName = name + ” ” + “Gaikwad”
or
var fullName = name.concat(” Gaikwad”)
Stuff String or Char
name.substring(0,3)+”123″+name.substring(3,name.length)
//sac123hin
// No direct method to stuff string/char in string
Stat- counting
chars
name.length
words
name.split(” “).length
Char at position
name.charAt(0) //s
Check Substring
name.includes(“chi”) // true
Get first occurrence index or last occurrence index of other string resp.
name.indexOf(“sa”)
name.lastIndexOf(“hi”)
Extract another string
name.slice(2) // chin
Trim whitespace
name.trim() // removes whitespace ” sachin ” to “sachin”
Export/Import from/to other data type
Array
name.split(” “) // gives array
nameArray.join() // gives string
Number
parseInt(“123”)// string to integer
parseFloat(“12.3”) // string to float
“”+123 // number to string