【问题标题】:Replace text in template with javascript用 javascript 替换模板中的文本
【发布时间】:2019-09-19 02:56:44
【问题描述】:

我正在处理收据。

我有一个html模板:

var Mytemplate= "Test Receipt
The receipt will be used tomorrow.
##start##  A
   B   C
   D
##end##
Here is more text"

在运行时,我需要将 '##start##' 到 '##end##' 的所有内容(包括这些术语)替换为其他字符串。

我正在使用下面的代码来提取文本:

String.prototype.extract = function(prefix, suffix) {
    s = this;
    var i = s.indexOf(prefix);
    if (i >= 0) {
        s = s.substring(i + prefix.length);
    }
    else {
        return '';
    }
    if (suffix) {
        i = s.indexOf(suffix);
        if (i >= 0) {
            s = s.substring(0, i);
        }
        else {
          return '';
        }
    }
    return s;
    };

var extracted_text=Mytemplate.extract("##start##","##end##");
var newContent=function(){
    var newText=make_something_with(extracted_text)  
    return newText||"This is my new content"
  }

如何用我的 newContent 替换 '##start##' 到 '##end##' 的内容? 是否可以使用正则表达式更好地完成这项任务?

【问题讨论】:

  • 您可以使用正则表达式来执行此操作。 Mytemplate.replace(/##start##(.|\n)*##end##/gm, 'the content you want to replace it'); regex101.com/r/5CaO4W/1
  • 究竟是什么不起作用? extract 应该给出所需的字符串。我唯一能看到的是newContent 是一个函数而不是文本。您可以将extracted_text 作为参数发送给newContent 并调用它。
  • @Radonirina Maminiaina 谢谢,它的工作。我的真实模板要复杂一些。我必须先逃避它吗?如果是,我该怎么做?

标签: javascript regex


【解决方案1】:

您可以利用 String 对象的 substr() 方法在字符串中获取 ##start## 和 ##end## 的起始索引,复制所需部分并使用 ## 之前的文本创建一个新字符串start##、新文本和##end##之后的文本。

var Mytemplate = "Test Receipt The receipt will be used tomorrow.##start##  A   B   C   D##end##Here is more text"
function replace(text, start, end, newText) {
  var tempString = text.substr(0, text.indexOf(start));
  var tempString2 = text.substr(text.indexOf(end) + end.length, text.length)
  return tempString + newText + tempString2;
}
console.log(Mytemplate);
Mytemplate = replace(Mytemplate, "##start##", "##end##", "this is some new text");
console.log(Mytemplate);

【讨论】:

    猜你喜欢
    • 2015-06-11
    • 1970-01-01
    • 2013-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-12
    • 2021-03-06
    • 2021-05-22
    相关资源
    最近更新 更多