JavaScript:如何替换两个标记变量之间的字符串
Looking at your example, you want to swap out the entire substring starting with My and ending with So (including those markers) with your new string Pussy Cat Very. Here are two reliable ways to do this in JavaScript:
Method 1: String Manipulation (No Regex Needed)
This approach uses basic string methods to locate the markers and build the new string step by step. It’s great if you want to avoid regex complexity, especially if your markers might contain special characters like . or *.
function replaceBetweenMarkers(str, startMarker, endMarker, replacement) { // Find the position of the start marker const startIndex = str.indexOf(startMarker); if (startIndex === -1) return str; // Start marker not found, return original // Find the position of the end marker, starting after the start marker const endIndex = str.indexOf(endMarker, startIndex + startMarker.length); if (endIndex === -1) return str; // End marker not found, return original // Build the new string: before start marker + replacement + after end marker return str.slice(0, startIndex) + replacement + str.slice(endIndex + endMarker.length); } // Example usage const str_before = 'I Love My Cat So Much'; const start_mark = 'My'; const end_mark = 'So'; const str_replace = 'Pussy Cat Very'; const result = replaceBetweenMarkers(str_before, start_mark, end_mark, str_replace); console.log(result); // Output: "I Love Pussy Cat Very Much"
How it works:
indexOf(startMarker)locates where the start marker begins in the string.indexOf(endMarker, startIndex + startMarker.length)ensures we look for the end marker after the start marker, avoiding accidental matches of end markers that come before the start.slice()splits the original string into three parts: everything before the start marker, your replacement text, and everything after the end marker. We concatenate these to get the final result.
Method 2: Regular Expression Approach
If you prefer a more concise solution, regex works well here—just make sure to escape any special characters in your markers first (since regex treats characters like $ or ( as special commands).
// Helper function to escape regex special characters function escapeRegExp(string) { return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } function replaceBetweenMarkersRegex(str, startMarker, endMarker, replacement) { const escapedStart = escapeRegExp(startMarker); const escapedEnd = escapeRegExp(endMarker); // Regex pattern to match from start marker to end marker (inclusive) const regex = new RegExp(`${escapedStart}.*?${escapedEnd}`, 's'); // Replace the matched substring with the replacement text return str.replace(regex, replacement); } // Example usage const str_before = 'I Love My Cat So Much'; const start_mark = 'My'; const end_mark = 'So'; const str_replace = 'Pussy Cat Very'; const result = replaceBetweenMarkersRegex(str_before, start_mark, end_mark, str_replace); console.log(result); // Output: "I Love Pussy Cat Very Much"
How it works:
escapeRegExp()converts any special characters in your markers into literal characters (so$becomes\$, etc.).- The regex pattern
escapedStart.*?escapedEndmatches the start marker, any characters in between (the.*?is non-greedy, so it stops at the first occurrence of the end marker), and the end marker. - The
's'flag allows the regex to match newlines if your string has line breaks.
Both methods will give you the exact result you’re looking for. The string manipulation method is more beginner-friendly, while regex is shorter once you have the escape helper function.
内容的提问来源于stack exchange,提问作者Murphy'z law




