Skip to main content

JavaScript Strings Manipulation

Learn to find out the length of a JavaScript String to match a pattern. In this how-to guide, we will explore attributes and methods for String object type in detail.

Find Length of String

Use length attribute on String variable or literal

var smallString = "A Small Length String";
console.log("Length of String "A Small Length String" is "+ smallString.length);
/* Finding Length directly on String literal */
console.log("Length of String "String Literal" is "+ "String Literal".length);
/* Empty String */
console.log("Length of String "" is "+ "".length);


Length of String "A Small Length String" is 21
Length of String "String Literal" is 14
Length of String "" is 0

Concatenate / Combine String

Creating a new string from two or more Strings is one most common codes we write in JavaScript. We have three ways to do that.

Use Assignment Operators (+ or +=)

/* Concatenate String using assignment operator */

var string1 = "abc", string2 = "def", string3 = "ghi";
var concatenatedString1 = string1 + string2 + string3;"concatenatedString1 = " + concatenatedString1);

/* Output:  concatenatedString1 = abcdefghi */

var concatenatedString2 = 'I-' + 'am-' + 'good'; // Its valid too "I-" + "am-" + "good""concatenatedString2 = " + concatenatedString2);

/* Output:  concatenatedString2 = I-am-good */" abc + def + ghi = "+ ("abc" + "def" + "ghi"));

/* Output: abc + def + ghi = abcdefghi */

/* Splitting a String into multiple lines using assignment operator */

var stringMultiline1 = "This is visual line 1 " +
                       "This is visual line 2 " +
                       "This is visual line 3";"stringMultiline1 = " + stringMultiline1);

/* Output: stringMultiline1 = This is visual line 1 This is visual line 2 This is visual line 3  */

/* Concatinating String to a variable in multiple steps */

var concatenatedString3 = "Initial Value1";

concatenatedString3 += " Value 2";
concatenatedString3 += " Value 3";"concatenatedString3 = " +concatenatedString3);

/* Output: concatenatedString3 = Initial Value1 Value 2 Value 3 */

Use concat() method

/* Concatenate using concat method */
var name = "Mrityunjay";
var companyName = "Google Inc.";
var newStringByConcat = ("Hi my name is ").concat(name).concat(" and I worked at ").concat(companyName);"newStringByConcat: "+newStringByConcat);

/* Output: newStringByConcat: Hi my name is Mrityunjay and I worked at Google Inc. */

Use Array of String  join() method

var personalIntroStringArray = \["Hi my name is ", "Mrityunjay", " and I worked at ", "Google Inc."\];

var newStringByArrayJoin = personalIntroStringArray.join();"newStringByArrayJoin: "+ newStringByArrayJoin); 
/\* Result: newStringByArrayJoin: Hi my name is ,Mrityunjay, and I worked at ,Google Inc. \*/
// Notice comma in between concatenated Strings

{{% alert note %}} Pro Tip: Use assignment operator based String Concatenation for best performance. It performs substantially better in compare to other 2 ways.  Performance Test {{% /alert %}}

Split String

Let me tell you how Split work in JavaScript (split function):

  1. You have one String
  2. You can select one or more characters around which we Split the String
  3. Selected character(s) work as a breaking point (separator) and doesn't eliminate from the resultant array of String
  4. We may limit the length of the resultant array of String after split

Use the Split function as shown below:

StringVariable.split(Separator, n)

Separator can be one character, String, or regular expression.

n is limited by the size of the resultant array.

var stringGoingToSplit = "Tag1,Tag2,Tag3,Tag4,Tag5";

/* Limit same as String Array Size */
var splittedStringArray1 = stringGoingToSplit.split(",", 5);
/* Result:  splittedStringArray1 = \["Tag1", "Tag2", "Tag3", "Tag4", "Tag5"\] */

/* Limit less than String Array Size\*/
var splittedStringArray2 = stringGoingToSplit.split(",", 3);
/* Result:  splittedStringArray2 = \["Tag1", "Tag2", "Tag3"\]\*/

/* Limit exceed String Array Size */
var splittedStringArray3 = stringGoingToSplit.split(",", 7);
/* Result:  splittedStringArray2 = \["Tag1", "Tag2", "Tag3, "Tag4", "Tag5"\] */

/* No limit */
var splittedStringArray4 = stringGoingToSplit.split(",");
/* Result:  splittedStringArray4 = \["Tag1", "Tag2", "Tag3, "Tag4", "Tag5"\] */

Find the occurrence of Search Phrase in String

Let's say we want to solve the following problems:

  1. Find if a string ends with the character 'm' or starts with 'm'.
  2. Find if an address String consists of the phrase 'street no 7'.
  3. Find if the phrase 'black' came thrice in one paragraph String.

All the above problems can be solved, if we can find indexes (which can have many occurrences) of search phrase first character in String.

We have a few methods available in JavaScript which can help in solving these problems.

1. String.indexOf(searchPhrase[, startIndex])


searchPhrase is a string consisting of one or more characters that we are finding in a String?

startIndex [optional] is the index of the character in String, there onward, searchPhrase will be searched. If startIndex is not given or less than 0, 0 is considered by default. If startIndex is out of the range (larger than max String size) -1 index will be returned.


It returns integer value; -1 if phrase not found; >=0 representing the index at which searchPhrase first character found;

Few Usage Examples:

// In the String "My name is James Wisely" phrase "is" has came twice 
// First at index 8 and second at index 18"My name is James Wisely".indexOf("is"));
// Result: 8"My name is James Wisely".indexOf("is", 9));
// Result: 18
// custom start index 9 has been set after first occurrence index 8"My name is James Wisely".indexOf("is", 19));
// Result: -1
// custom start index 19 has been set and there is no occurence of search phrase"My name is James Wisely".indexOf("is", 24));
// Result: -1
// Start Index has been set to 24, which is out of the scope (max index for the searchable String is 22)"My name is James Wisely".indexOf("is", 0));
// Result: 8
// Start Index has been set to 0, Which is default start Index value too"My name is James Wisely".indexOf("is", -1));
// Result 8
// Start Index has been set to -1, Which is non existant index, method will automatically ignore the last index and search from 0 index.

2. String.lastIndexOf(searchPhrase[, startIndex]);


searchPhrase is a string consisting of one or more characters that we are finding in a String?

startIndex[optional] is the index of the character in String, from where in reverse order, searchPhrase will be searched. Say l is the length of searched String. l - 1 is the default value of startIndex. If startIndex is greater than equal to l, l-1 will be considered as the value of startIndex. If startIndex is less than 0, then -1 will be returned.


It returns integer value; -1 if phrase not found; >=0 representing the index at which searchPhrase the first character found;

Few usage examples:"My name is James Wisely".lastIndexOf("is"));
// Result: 18
// No searchIndex has been provided, max index 22 has been considered by default"My name is James Wisely".lastIndexOf("is", 3));
// Result: -1
// searhIndex is 3, well no occurence of is available in reverse order"My name is James Wisely".lastIndexOf("is",14));
// Result: 8
// searchIndex is 14, one occurence of is available at index 8"My name is James Wisely".lastIndexOf("is",23));
// Result: 18
// searchIndex is 23 greater than max index 22, no error will be thrown and search perform with index 22"My name is James Wisely".lastIndexOf("is",-1));
// Result: -1
// searchIndex is -1 less than minimum index 0, no error will be thrown and search yields -1


Popular posts from this blog

Working with request header in Jersey (JAX-RS) guide

In the  previous post , we talked about, how to get parameters and their values from the request query string. In this guide learn how to get request header values in Jersey (JAX-RS) based application. We had tested or used the following tools and technologies in this project: Jersey (v 2.21) Gradle Build System (v 2.9) Spring Boot (v 1.3) Java (v 1.8) Eclipse IDE This is a part of  Jersey (JAX-RS) Restful Web Services Development Guides series. Please read Jersey + Spring Boot getting started guide . Gradle Build File We are using Gradle for our build and dependency management (Using Maven rather than Gradle is a very trivial task). File: build.gradle buildscript { ext { springBootVersion = '1.3.0.RELEASE' } repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } } apply plugin: 'java' apply plugin: 'eclipse' a

Ajax Cross Domain Resource Access Using jQuery

Some time back in our project we faced a problem while making an Ajax call using jQuery. Chrome Browser console had given some weird error message like below when we try to access one of our web pages: When we try to access the same web page in the Firefox browser, it doesn't give any error in the console but some parsing error occurred. In our case, we were accessing XML as an Ajax request resource. I was curious to check if the non-XML cross-domain resource was successfully loading or not. But finally, I realized that it is not going through. jersey-spring-boot-quick-starter-guide In our Ajax call, requesting domain was not the same as the requested URL domain. $.ajax({ url: "" , type : "get" , success: function (response) { alert( "Load was performed." ); }, error : function (xhr, status) {

FastAPI first shot

Setup on my Mac (Macbook Pro 15 inch Retina, Mid 2014) Prerequisite Python 3.6+ (I used 3.7.x. I recently reinstalled OS after cleaning up disk, where stock Python 2.7 was available. I installed Pyenv and then used it to install 3.7.x). I already had a git repo initialized at Github for this project. I checked that out. I use this approach to keep all the source code safe or at a specific place 😀. I set the Python version in .python-version file. I also initialize the virtual environment using pyenv in venv folder. I started the virtual environment. FastAPI specific dependencies setup Now I started with basic pip commands to install dependency for the project. I saved dependencies in requirements.txt  the file. Minimal viable code to spin an API Server FastAPI is as cool as NodeJS or Go Lang (?) to demonstrate the ability to spin an API endpoint up and running in no time. I had the same feeling for the Flask too, which was also super cool. app/ from typing i