There is a possibility while working with javascript, that you may want to get substring after a character, so in this article, I have mentioned few possible ways to get substring from string after a character using javascript.
1. Using Split()
Using split method, you can keep the original string as it is and get array of string by using .split('character_to_split')
Example:
const inputString = "Hello-World";
const delimiter = "-";
const substrings = inputString.split(delimiter);
const substringAfterDelimiter = substrings.slice(1).join(delimiter);
console.log(substringAfterDelimiter);
// Output: "World"
2. Using Substring and IndexOf
The substring
method in JavaScript returns a part of a string between the start and end indexes.
So to get the IndexOf of character from which we want to split the string, we will use IndexOf
method also
Example:
const inputString = "Hello-World";
const delimiter = "-";
const delimiterIndex = inputString.indexOf(delimiter);
const substringAfterDelimiter = inputString.substring(delimiterIndex + delimiter.length);
console.log(substringAfterDelimiter);
// Output: "World"
In the above Javascript code, we have used the substring method to get the substring after the dash. To get the index of the dash, we used the indexOf() method.
3. Using substring() method and lastIndexOf()
This method is similar to above mentioned method, we can also use lastIndexOf instead of IndexOf method.
Example:
const inputString = "Hello-World-Hello";
const delimiter = "-";
const delimiterIndex = inputString.lastIndexOf(delimiter);
const substringAfterDelimiter = inputString.substring(delimiterIndex + delimiter.length);
console.log(substringAfterDelimiter);
// Output: "Hello"
4. Using Regular Expression with 'match'
We can also use Regex with match to get substring after a character
Example:
const inputString = "Hello-World";
const delimiter = "-";
const pattern = new RegExp(`(?:${delimiter})(.*)`);
const match = inputString.match(pattern);
if (match) {
const substringAfterDelimiter = match[1];
console.log(substringAfterDelimiter);
}
// Output: "World"
5. Using split with Pop
Once you split the stirng, you can use pop method, to get the substring after character.
Here is an example:
// javascript substring after character
var str = "Hello-World";
// using pop()
var substr = str.split("-").pop();
console.log(substr); // output: World
So these were all possible methods to get substring after a character using Javascript.
You may also like to read:
Find Element based on Data-Attribute using Javascript or jQuery
Various ways to convert date to Unix Timestamp in Javascript
How can I check Typescript version in Visual Studio?