How do you end a string with another string in javascript?

Examples

Extract a substring from text:

let text = "Hello world!";
let result = text.substring(1, 4);

Try it Yourself »

Start from position 2:

let result = text.substring(2);

Try it Yourself »

More examples below.


Definition and Usage

The substring() method extracts characters, between two indices (positions), from a string, and returns the substring.

The substring() method extracts characters from start to end (exclusive).

The substring() method does not change the original string.

If start is greater than end, arguments are swapped: (4, 1) = (1, 4).

Start or end values less than 0, are treated as 0.


Syntax

string.substring(start, end)

Parameters

Parameter Description
start Required.
Start position.
First character is at index 0.
end Optional.
End position (up to, but not including).
If omitted: the rest of the string.

Return Value

Type Description
A string A string containing the extracted characters.


More Examples

If start is greater than end, parameters are swapped:

let result = text.substring(4, 1);

Try it Yourself »

If "start" is less than 0, it will start from index 0:

let result = text.substring(-3);

Try it Yourself »

Only the first:

let result = text.substring(0, 1);

Try it Yourself »

Only the last:

let result = text.substring(text.length - 1);

Try it Yourself »


Browser Support

substring() is an ECMAScript1 (ES1) feature.

ES1 (JavaScript 1997) is fully supported in all browsers:

Chrome IE Edge Firefox Safari Opera
Yes Yes Yes Yes Yes Yes


Examples

Check if a string ends with "world":

let text = "Hello world";
let result = text.endsWith("world");

Try it Yourself »

let text = "Hello World";
let result = text.endsWith("world");

Try it Yourself »

More examples below.


Definition and Usage

The endsWith() method returns true if a string ends with a specified string.

Otherwise it returns false.

The endsWith() method is case sensitive.

See also the startswith() method.


Syntax

string.endsWith(searchvalue, length)

Parameters

Parameter Description
searchvalue Required.
The string to search for.
length Optional.
The length of the string to search.
Default value is the length of the string.

Return Value

Type Description
A boolean true if the string ends with the value, otherwise false.


More Examples

Check if the 11 first characters of a string ends with "world":

let text = "Hello world, welcome to the universe.";
text.endsWith("world", 11);

Try it Yourself »


Browser Support

endsWith() is an ECMAScript6 (ES6) feature.

ES6 (JavaScript 2015) is supported in all modern browsers:

Chrome Edge Firefox Safari Opera
Yes Yes Yes Yes Yes

endsWith() is not supported in Internet Explorer 11 (or earlier).



How do you end a string with another string in javascript?

In this article, I’ll explain how to solve freeCodeCamp’s “Confirm the Ending” challenge. This involves checking whether a string ends with specific sequence of characters.

There are the two approaches I’ll cover:

  1. using the substr() method
  2. using endsWith() method

The Algorithm Challenge Description

Check if a string (first argument, str) ends with the given target string (second argument, target).

This challenge can be solved with the .endsWith() method, which was introduced in ES2015. But for the purpose of this challenge, we would like you to use one of the JavaScript substring methods instead.

function confirmEnding(string, target) {
  return string;
}
confirmEnding("Bastian", "n");

ADVERTISEMENT

Provided test cases

confirmEnding("Bastian", "n") should return true.

confirmEnding("Connor", "n") should return false.

confirmEnding("Walking on water and developing software from a specification are easy if both are frozen", "specification") should return false.

largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]]) should return [9, 35, 97, 1000000].

confirmEnding("He has to give me a new name", "name")should return true.
confirmEnding("Open sesame", "same") should return true.

confirmEnding("Open sesame", "pen") should return false.

confirmEnding("If you want to save our world, you must hurry. We dont know how much longer we can withstand the nothing", "mountain") should return false.

Do not use the built-in method .endsWith() to solve the challenge.

ADVERTISEMENT

Approach #1: Confirm the Ending of a String With Built-In Functions — with substr()

For this solution, you’ll use the String.prototype.substr() method:

  • The substr() method returns the characters in a string beginning at the specified location through the specified number of characters.

Why are you using string.substr(-target.length)?

If the target.length is negative, the substr() method will start the counting from the end of the string, which is what you want in this code challenge.

You don’t want to use string.substr(-1) to get the last element of the string, because if the target is longer than one letter:

confirmEnding("Open sesame", "same")

…the target won’t return at all.

So here string.substr(-target.length) will get the last index of the string ‘Bastian’ which is ‘n’.

Then you check whether string.substr(-target.length) equals the target (true or false).


function confirmEnding(string, target) {
  // Step 1. Use the substr method
  if (string.substr(-target.length) === target) {
  
  // What does "if (string.substr(-target.length) === target)" represents?
  // The string is 'Bastian' and the target is 'n' 
  // target.length = 1 so -target.length = -1
  // if ('Bastian'.substr(-1) === 'n')
  // if ('n' === 'n')
  
  // Step 2. Return a boolean (true or false)
    return true;
  } else {
    return false;
  }
}

confirmEnding('Bastian', 'n');

Without comments:


function confirmEnding(string, target) {
  if (string.substr(-target.length) === target) {
    return true;
  } else {
    return false;
  }
}
confirmEnding('Bastian', 'n');

You can use a ternary operator as a shortcut for the if statement:

(string.substr(-target.length) === target) ? true : false;

This can be read as:

if (string.substr(-target.length) === target) {
    return true;
} else {
    return false;
}

You then return the ternary operator in your function:


function confirmEnding(string, target) {
  return (string.substr(-target.length) === target) ? true : false;
}
confirmEnding('Bastian', 'n');

You can also refactor your code to make it more succinct by just returning the condition:

function confirmEnding(string, target) {
  return string.substr(-target.length) === target;
}
confirmEnding('Bastian', 'n');

ADVERTISEMENT

Approach #2: Confirm the Ending of a String With Built-In Functions — with endsWith()

For this solution, you’ll use the String.prototype.endsWith() method:

  • The endsWith() method determines whether a string ends with the characters of another string, returning true or false as appropriate. This method is case-sensitive.
function confirmEnding(string, target) {
  // We return the method with the target as a parameter
  // The result will be a boolean (true/false)
  return string.endsWith(target); // 'Bastian'.endsWith('n')
}
confirmEnding('Bastian', 'n');

I hope you found this helpful. This is part of my “How to Solve FCC Algorithms” series of articles on the freeCodeCamp Algorithm Challenges, where I propose several solutions and explain step-by-step what happens under the hood.

Three ways to repeat a string in JavaScript
In this article, I’ll explain how to solve freeCodeCamp’s “Repeat a string repeat a string” challenge. This involves…

Three Ways to Reverse a String in JavaScript
This article is based on Free Code Camp Basic Algorithm Scripting “Reverse a String”

Three Ways to Factorialize a Number in JavaScript
This article is based on Free Code Camp Basic Algorithm Scripting “Factorialize a Number”

Two Ways to Check for Palindromes in JavaScript
This article is based on Free Code Camp Basic Algorithm Scripting “Check for Palindromes”.

Three Ways to Find the Longest Word in a String in JavaScript
This article is based on Free Code Camp Basic Algorithm Scripting “Find the Longest Word in a String”.

Three Ways to Title Case a Sentence in JavaScript
This article is based on Free Code Camp Basic Algorithm Scripting “Title Case a Sentence”.

If you have your own solution or any suggestions, share them below in the comments.

Or you can follow me on Medium, Twitter, Github and LinkedIn, right after you click the green heart below ;-)

‪#‎StayCurious‬, ‪#‎KeepOnHacking‬ & ‪#‎MakeItHappen‬!

ADVERTISEMENT

Additional Resources

  • substr() method — MDN
  • endsWith() method — MDN
  • Ternary Operator — MDN


Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started

How do you end a string in JavaScript?

Two ways to confirm the ending of a String in JavaScript.
using the substr() method..
using endsWith() method..

How do you check if a string ends with another string JavaScript?

The endsWith() method returns true if a string ends with a specified string. Otherwise it returns false . The endsWith() method is case sensitive.

What is replace () in JavaScript?

The replace() method searches a string for a value or a regular expression. The replace() method returns a new string with the value(s) replaced. The replace() method does not change the original string.

How do substring () and substr () differ?

The difference between substring() and substr() The two parameters of substr() are start and length , while for substring() , they are start and end . substr() 's start index will wrap to the end of the string if it is negative, while substring() will clamp it to 0 .