Javascript string functions

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


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

 

Auto Slug field in Django

While designing database, many times we need slug field which we populate from some other field of the same model.

We can set auto slug field so that we don’t need to code in order to populate slug field while insert or update.

You can use the field AutoSlugField from module django-autoslug.

1. Install module django-autoslug.
pip install django-autoslug

2. Import in models file where your model exists.
from autoslug import AutoSlugField

3. Set field in model
E.g.
title = models.CharField(max_length=100)
slug = AutoSlugField(populate_from=’title’,default=None)