如何在无if语句的情况下从字符串末尾提取并移除数组?
if Statements) Great question! Ditching clunky if statements for this kind of string manipulation can make your code more concise and expressive. Here are a couple of clean, if-free solutions to handle both scenarios (strings with or without a trailing array):
1. Regular Expression + Destructuring Assignment
This approach uses a regex to capture both the main text content and the trailing array in one go, then leverages destructuring with default values to handle cases where no array exists:
const value = " Have you ever * looked* sam [5, 6]"; // Match the main text and optional trailing array const [textPart = value, arrayStr = ''] = value.match(/^(.*?)\s*(\[.*\])$/) || []; // Parse the array string if it exists, default to empty array otherwise const resultArray = arrayStr ? JSON.parse(arrayStr) : []; console.log(textPart); // Output: " Have you ever * looked* sam" console.log(resultArray); // Output: [5, 6]
How it works:
- The regex
^(.*?)\s*(\[.*\])$does two things:^(.*?)captures all text up to the start of the trailing array (non-greedy match to avoid overcapturing)\s*(\[.*\])$captures the array itself, including any leading whitespace before it
- If no array is present,
value.match()returnsnull, so we use|| []to fall back to an empty array. The default values (textPart = value,arrayStr = '') ensure we keep the original string and an empty array in this case.
2. Last Index Lookup + Ternary Operators
If regex feels overkill, you can use lastIndexOf to find the start of the trailing array, then use ternary expressions (which are expressions, not if statements) to split and parse the content:
const value = " Have you ever * looked* sam"; const bracketStart = value.lastIndexOf('['); const textPart = bracketStart !== -1 ? value.slice(0, bracketStart).trimEnd() : value; const arrayStr = bracketStart !== -1 ? value.slice(bracketStart) : ''; const resultArray = arrayStr ? JSON.parse(arrayStr) : []; console.log(textPart); // Output: " Have you ever * looked* sam" console.log(resultArray); // Output: []
How it works:
lastIndexOf('[')finds the position of the last opening bracket (ensuring we target the trailing array, not any brackets inside the main text)- Ternary operators handle both cases (bracket found or not) in a concise, expression-based way
trimEnd()cleans up any extra whitespace between the main text and the array
Both of these approaches avoid explicit if blocks, keeping your code more declarative and easier to read. Just make sure your trailing array is valid JSON (e.g., uses double quotes for strings if present) so JSON.parse works correctly!
内容的提问来源于stack exchange,提问作者Sara Ree

