有没有一种方法可以通过Javascript中的索引更改子字符串

时间:2020-04-29 12:14:42

标签: javascript string

我目前正在使用JavaScript开发自己的markdown代码,我想知道是否可以将文本中的子字符串更改为这样的另一个字符串:

“ **随机文本**”->“ <strong> random text </strong>

在这种情况下,类似my_text.replaceSubString(0,2,"<strong>")的东西应该起作用。

我还使用令牌索引来查找需要在文本中进行更改的位置,以便不能使用正则表达式。

2 个答案:

答案 0 :(得分:0)

您可以尝试类似的方法。但是,不建议覆盖String类。更好地创建util函数

String.prototype.mdReplace  = function(tag) { 
  return this.replace(/\*\*(.+?)\*\*/g, `<${tag}>$1</${tag}>`)
}
console.log("** test **".mdReplace("strong"))

答案 1 :(得分:0)

这是您可能不应该重新发明的功能,但是...如果您不想使用正则表达式,则可以尝试这样的功能。

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"