JavaScript Strings Manipulation

JavaScript String methods for find, concatenate, split, join String array join and others with sample code.

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);

Result:

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;
console.info("concatenatedString1 = " + concatenatedString1);

/* Output:  concatenatedString1 = abcdefghi */

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

/* Output:  concatenatedString2 = I-am-good */

console.info(" 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";

console.info("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";

console.info("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);

console.info("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();

console.info("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])

Arguments:

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.

Return:

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

console.info("My name is James Wisely".indexOf("is"));
// Result: 8

console.info("My name is James Wisely".indexOf("is", 9));
// Result: 18
// custom start index 9 has been set after first occurrence index 8

console.info("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

console.info("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)

console.info("My name is James Wisely".indexOf("is", 0));
// Result: 8
// Start Index has been set to 0, Which is default start Index value too

console.info("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]);

Arguments:

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.

Return:

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

Few usage examples:

console.info("My name is James Wisely".lastIndexOf("is"));
// Result: 18
// No searchIndex has been provided, max index 22 has been considered by default

console.info("My name is James Wisely".lastIndexOf("is", 3));
// Result: -1
// searhIndex is 3, well no occurence of is available in reverse order

console.info("My name is James Wisely".lastIndexOf("is",14));
// Result: 8
// searchIndex is 14, one occurence of is available at index 8

console.info("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

console.info("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
JOIN OUR NEWSLETTER
And get notified everytime we publish a new blog post.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top