简体   繁体   English

如何替换字符串中由 {} 括起来的所有子字符串?

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

I have to address an algo problem with vanilla JS.我必须解决 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:所以在替换之后, stringExample应该是:

"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 . JS 小提琴演示

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:参考书目:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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