Return String

How To Remove Trailing Symbols and Punctuation

Updated 2021-07-06

Learn to remove any non-alphanumeric characters from the end of a string in JavaScript.

/**
 * Removes any non-alphanumeric characters from the end of a string.
 *
 * @param {string} text text to process
 * @returns {string} processed text
 */
function removeTrailingPunctuation(text) {
    const match = text.match(new RegExp(`[^a-zA-Z0-9]+$`));
    // No match found
    if (!match || !match.index) {
        return text;
    }
    // Return sliced text
    return text.slice(0, match.index);
}

If you need to localize the script to your own language, it should be easy to modify the regex to include local characters.