(str: string, options: VariableStringOptions = defaultOptions)
| 36 | * All elements with even indices are variable names, and those with odd indices are plain text. |
| 37 | */ |
| 38 | export function splitVariableString(str: string, options: VariableStringOptions = defaultOptions): string[] { |
| 39 | const splits: string[] = []; |
| 40 | let prevCutIndex = 0; // (Index of the character after the previous split end) |
| 41 | // Look for all "open" characters in the string |
| 42 | for (let i = 0; i < str.length; i++) { |
| 43 | if (str[i] === options.openChar) { |
| 44 | // Look for the next "close" character |
| 45 | const closeIndex = str.indexOf(options.closeChar, i + 1); |
| 46 | if (closeIndex >= 0) { |
| 47 | // Push preceding plain text |
| 48 | splits.push(str.substring(prevCutIndex, i)); |
| 49 | // Push variable name |
| 50 | splits.push(str.substring(i + 1, closeIndex)); |
| 51 | // Update index |
| 52 | prevCutIndex = closeIndex + 1; |
| 53 | } |
| 54 | } |
| 55 | } |
| 56 | // Add the remaining characters |
| 57 | if (prevCutIndex < str.length) { |
| 58 | splits.push(str.substring(prevCutIndex)); |
| 59 | } |
| 60 | // Done |
| 61 | return splits; |
| 62 | } |
| 63 | |
| 64 | const defaultOptions: VariableStringOptions = { |
| 65 | openChar: '<', |
no test coverage detected