-1

I am currently working on my own markdown code in javascript and I want to know if there is a way to change a substring in a text to another string like this :

"** random text **" -> "<strong> random text </strong>"

In this case something like this my_text.replaceSubString(0,2,"<strong>") should work.

I am also using tokens index to find where in the text I need to make a change so I can't use regex.

Estout
  • 1
  • 1
    Regex would be easier `text.replace(/\*\*(.*?)\*\*/g, '$1')`.. how are you storing your token indexes? And how are you looping over them? – Washington Guedes Apr 29 '20 at 12:19
  • This? https://stackoverflow.com/questions/1431094/how-do-i-replace-a-character-at-a-particular-index-in-javascript – Fasani Apr 29 '20 at 12:19

2 Answers2

0

You can try something similar. However, not recommended to override the String class. Better create util function

String.prototype.mdReplace  = function(tag) { 
  return this.replace(/\*\*(.+?)\*\*/g, `<${tag}>$1</${tag}>`)
}
console.log("** test **".mdReplace("strong"))
xdeepakv
  • 7,835
  • 2
  • 22
  • 32
0

This is a feature you probably shouldn't reinvent, but...if you don't want to use regex then you can try a function like this.

const replaceTokensWithTags = (str, token, tag) => {
    return str.split(token).map((v, index) => {
        return index % 2 ? tag + v + (tag[0] + '/' + tag.slice(1)): v;
    }).join('');
}

replaceTokensWithTags("I am also using **tokens** index to **find** where in the text I need to make a change so I can't use regex", '**', '<b>');

// becomes: "I am also using <b>tokens</b> index to <b>find</b> where in the text I need to make a change so I can't use regex"

replaceTokensWithTags("I am also using [b]tokens[b] index to [b]find[b] where in the [b]text I need[b] to make a change so I can't use regex", '[b]', '<b>');

becomes: "I am also using <b>tokens</b> index to <b>find</b> where in the <b>text I need</b> to make a change so I can't use regex"
Rainer Plumer
  • 3,693
  • 2
  • 24
  • 42