首页 > 解决方案 > 有没有办法在Javascript中通过索引更改子字符串

问题描述

我目前正在编写自己的 javascript 降价代码,我想知道是否有办法将文本中的子字符串更改为另一个字符串,如下所示:

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

在这种情况下,这样的事情my_text.replaceSubString(0,2,"<strong>")应该可以工作。

我还使用标记索引来查找我需要在文本中进行更改的位置,因此我不能使用正则表达式。

标签: javascriptstring

解决方案


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

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"

推荐阅读