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?

4
  • Refer this [link]stackoverflow.com/questions/11024971/… Commented Apr 30, 2019 at 12:39
  • 2
    you can use regex to do this. Mytemplate.replace(/##start##(.|\n)*##end##/gm, 'the content you want to replace it'); regex101.com/r/5CaO4W/1 Commented Apr 30, 2019 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. Commented Apr 30, 2019 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? Commented Apr 30, 2019 at 12:48

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.