簡體   English   中英

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

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

我必須解決 vanilla JS 的算法問題。 我有一個字符串:

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

我想用一系列替換來替換它(按順序)

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

所以在替換之后, stringExample應該是:

"my dog has 4 ears"

可以使用的一種方法如下:

 // 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 小提琴演示

這根本沒有健全性檢查,我也沒有探索過任何邊緣情況。 如果可能的話,我會認真推薦使用開源——並且經過充分測試、充分證明的——框架或模板庫。

參考:

參考書目:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM