[javascript] How to return part of string before a certain character?

If you look at the jsfiddle from question,

var str = "Abc: Lorem ipsum sit amet";
str = str.substring(str.indexOf(":") + 1);

This returns all characters after the :, how can I adjust this to return all the characters before the :

something like var str_sub = str.substr(str.lastIndexOf(":")+1); but this does not work.

This question is related to javascript substring

The answer is


In General a function to return string after substring is

_x000D_
_x000D_
function getStringAfterSubstring(parentString, substring) {_x000D_
    return parentString.substring(parentString.indexOf(substring) + substring.length)_x000D_
}_x000D_
_x000D_
function getStringBeforeSubstring(parentString, substring) {_x000D_
    return parentString.substring(0, parentString.indexOf(substring))_x000D_
}_x000D_
console.log(getStringAfterSubstring('abcxyz123uvw', '123'))_x000D_
console.log(getStringBeforeSubstring('abcxyz123uvw', '123'))
_x000D_
_x000D_
_x000D_


And note that first argument of subString is 0 based while second is one based.

Example:

String str= "0123456";
String sbstr= str.substring(0,5);

Output will be sbstr= 01234 and not sbstr = 012345


Another method could be to split the string by ":" and then pop off the end. var newString = string.split(":").pop();