如何获取字符串最后一个字母字符?实现非最后字母字符后加空格
Hey there! Let's break down your two questions and solve them step by step:
问题1:如何获取字符串中的最后一个字母字符?
To grab the last letter character in a string, the most straightforward approach is to iterate backward from the end of the string, checking each character until you find an alphabetic one (both uppercase and lowercase). Here's a practical code example:
function getLastLetterCharacter(str) { // Start from the last character and work backwards for (let i = str.length - 1; i >= 0; i--) { // Use a regex to check if the character is a letter if (/[a-zA-Z]/.test(str[i])) { return str[i]; } } // Return null if there are no letters in the string (adjust to empty string if needed) return null; } // Test cases console.log(getLastLetterCharacter("test")); // Output: "t" console.log(getLastLetterCharacter("test.")); // Output: "t" console.log(getLastLetterCharacter("hello123!")); // Output: "o" console.log(getLastLetterCharacter("123$%^")); // Output: null
This method is efficient because it stops as soon as it finds the target character, no need to iterate the entire string.
问题2:给每个字符添加空格,但最后一个字母字符除外
Your initial logic was on the right track, but using i === str.length - 1 only checks if you're at the very end of the string—not accounting for cases where the last character isn't a letter. We need to first find the index of the last alphabetic character, then adjust our condition based on that.
Here's the adjusted code:
var str = "test."; var result = ""; // Step 1: Find the index of the last letter character let lastLetterIndex = -1; for (let i = str.length - 1; i >= 0; i--) { if (/[a-zA-Z]/.test(str[i])) { lastLetterIndex = i; break; } } // Step 2: Build the result string for (var i = 0; i < str.length; i++) { // Add just the character if we're at the last letter or beyond it // Otherwise, add the character plus a space result += (i >= lastLetterIndex) ? str[i] : str[i] + " "; } console.log(result); // For "test" → Output: "t e s t" // For "test." → Output: "t e s t."
Quick logic breakdown:
- We first locate the last letter's position with a backward loop, storing its index in
lastLetterIndex. - When building the result, we skip adding a space for the last letter and any characters that come after it (like the period in "test."). This keeps letters spaced out while attaching trailing non-letter characters directly to the final letter.
If your goal is to add spaces between every character except the last letter (e.g., "test." becomes "t e s t . "), just tweak the condition to check only for the last letter's index:
result += (i === lastLetterIndex) ? str[i] : str[i] + " ";
Pick the version that fits your exact use case!
内容的提问来源于stack exchange,提问作者Moaaz Bhnas

