0

I am working in a receipt.

I have a html template as:

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

At runtime, I need replace all content from '##start##' until '##end##' including these terms to other string.

I am using the next code to extract the text:

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"
  }

How could I replace the content from '##start##' until '##end##' with my newContent? Is possible make better this task using Regex?

Luiz Alves
  • 2,575
  • 4
  • 34
  • 75
  • Refer this [link]https://stackoverflow.com/questions/11024971/jquery-how-to-replace-all-between-certain-characters – Thamarai T Apr 30 '19 at 12:39
  • 2
    you can use regex to do this. `Mytemplate.replace(/##start##(.|\n)*##end##/gm, 'the content you want to replace it')`; https://regex101.com/r/5CaO4W/1/ – Radonirina Maminiaina Apr 30 '19 at 12:39
  • What exactly is not working? `extract` should give the desired string. The only thing I can see is `newContent` is a function and not the text. You can send `extracted_text` as a parameter to `newContent` and call it. – adiga Apr 30 '19 at 12:43
  • @Radonirina Maminiaina Thank you, It´s work. My real template is a few more complicated. Do I have to escape it before? If yes, how could I do it? – Luiz Alves Apr 30 '19 at 12:48

1 Answers1

1

You can utilize the String objects' substr() method to get the start index of ##start## and ##end## inside your string, copy the desired parts and create a new string with the text before ##start##, the new text and the text after ##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);
obscure
  • 11,916
  • 2
  • 17
  • 36