【问题标题】:How can I prepend each block of text with an ascending letter of the alphabet?如何在每个文本块前面加上一个升序字母?
【发布时间】:2021-05-11 01:00:33
【问题描述】:

我在文本区域中有问题形式的字符串,然后是以下格式的答案:

THIS IS A QUESTION
- This is the 1st answer

THIS IS ANOTHER QUESTION
- This is another answer

HERE IS THE FINAL QUESTIONS
- Oh boy we are done!

我想让用户选择输出问题和答案的成绩单,并在问题行前按升序排列,如下所示:

A. THIS IS A QUESTION
- This is the 1st answer

B. THIS IS ANOTHER QUESTION
- This is another answer

C. HERE IS THE FINAL QUESTIONS
- Oh boy we are done!

我对 javascript 正则表达式没有经验,但我已经了解了

(/.*[\s]/gm)

但它不能很好地捕获空行之间的组,我也无法弄清楚如何循环遍历我的大写字母数组并在匹配时添加它们。

感谢您的帮助!

【问题讨论】:

    标签: javascript regex replace match


    【解决方案1】:

    使用替换函数来跟踪最近替换的字符代码 - 以 64 开头(65 对应于 A,66 对应于 B,等等)。

    对于正则表达式本身,只需匹配行首后跟一个单词字符 - 所以,一个单词边界:

    const str = `THIS IS A QUESTION
    - This is the 1st answer
    
    THIS IS ANOTHER QUESTION
    - This is another answer
    
    HERE IS THE FINAL QUESTIONS
    - Oh boy we are done!`;
    
    let lastCharCode = 64;
    
    const result = str.replace(/^\b/gm, () => String.fromCharCode(++lastCharCode) + '. ');
    console.log(result);

    【讨论】:

      猜你喜欢
      • 2015-04-01
      • 2014-12-04
      • 1970-01-01
      • 1970-01-01
      • 2015-06-21
      • 2021-04-23
      • 1970-01-01
      • 2022-01-26
      • 1970-01-01
      相关资源
      最近更新 更多