Luiz Alves
Luiz Alves

Reputation: 2645

Replace text in template with javascript

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?

Upvotes: 0

Views: 901

Answers (1)

obscure
obscure

Reputation: 12891

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

Upvotes: 1

Related Questions