简体   繁体   中英

How to replace all substrings enclosed by {} in a string?

I have to address an algo problem with vanilla JS. I have a string:

let stringExample = "my {cat} has {2} ears";

And I want to replace it (in order) with an array of replacements

const replaceArray = ["dog", "4"];

So that after the replacement, the stringExample should be:

"my dog has 4 ears"

One approach that can be used is as follows:

 // a sample of Strings and their corresponding replacement-arrays: let string1 = "my {cat} has {2} ears", arr1 = ["dog", "4"], string2 = "They call me ~Ishmael~", arr2 = ['Susan'], string3 = "It is a #@truth@# #@universally acknowledged@#...", arr3 = ['questionable assertion', 'oft cited']; // here we use a named Arrow function which takes three arguments: // haystack: String, the string which features the words/characters to // be replaced, // needles: Array of Strings with which to replace the identified // groups in the 'haystack', // Array of Strings, these strings represent the characters with // which the words/characters to be replaced may be identified; // the first String (index 0) is the character marking the begining // of the capture group, and the second (index 1) indicates the // end of the captured group; this is supplied with the default // curly-braces: const replaceWords = (haystack, needles, delimiterPair = ['{', '}']) => { // we use destructuring assignment, to assign the string at // index 0 to the 'start' variable, the string at index 1 to // the 'end' variable; if no argument is provided the default // curly-braces are used/assigned: const [start, end] = delimiterPair, // here we construct a regular expression, using a template // string which interpolates the variables within the string; // the regular expression is composed of: // 'start' (eg: '{') //.+: any character that appears one or more times, //? : lazy quantifier so the expression matches the // shortest possible string, // 'end' (eg: '}'), // matched with the 'g' (global) flag to replace all // matches within the supplied string. // this gives a regular expression of: /{.+?}/g regexp = new RegExp(`${start}.+?${end}`, 'g') // here we compose a String using the template literal, to // interpolate the 'haystack' variable and also a tab-character // concatenated with the result returned by String.prototype.replace() // we use an anonymous function to supply the replacement-string: // return `"${haystack}":\t` + haystack.replace(regexp, () => { // here we remove the first element from the array of replacements // provided to the function, and return that to the string as the // replacement: return needles.shift(); }) } console.log(replaceWords(string1, arr1)); console.log(replaceWords(string2, arr2, ['~', '~'])); console.log(replaceWords(string3, arr3, ['#@', '@#']));

JS Fiddle demo .

This has no sanity checks at all, nor have I explored to find any edge-cases. If at all possible I would seriously recommend using an open source – and well-tested, well-proofed – framework or templating library.

References:

Bibliography:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM