To cut a string before a specific character, call the substring()
method. Pass 0 as the starting index and index position of the specific character as parameters to the substring()
method. The substring() method will return a string before the specific character.
The following JavaScript code cuts a string before a specific character:
let str = 'great-grandmother'; let before = str.substring(0, str.indexOf('-')); console.log(before); //"great"
In this example, the specific character is hyphen, but it could be underscore, comma, and others.
The index position of the specific character is obtained using the string indexOf() method. If the character is present in the string, the indexOf()
method returns its index position; otherwise, it returns -1.
let str = "great-grandmother"; console.log(str.indexOf('-')); //5
An alternative approach to cut a string before a specific character is to use the string slice() method.
let str = 'great-grandmother'; let before = str.slice(0, str.indexOf('-')); console.log(before); //"great"
Note: The substring()
and slice()
methods are used to get a part of the string, but they have some differences. You can read more about the differences on this web page.
Using the split() method, you can cut a string before a specific character. The string split()
method returns an array of substrings. The array element at index position 0 is the string that is before a specific character.
let str = 'great-grandmother'; let before = str.split('-')[0]; console.log(before); //"great"