javascript - 有没有办法在Javascript中通过索引更改子字符串
问题描述
我目前正在编写自己的 javascript 降价代码,我想知道是否有办法将文本中的子字符串更改为另一个字符串,如下所示:
"** 随机文本 **" -> " <strong> random text </strong>
"
在这种情况下,这样的事情my_text.replaceSubString(0,2,"<strong>")
应该可以工作。
我还使用标记索引来查找我需要在文本中进行更改的位置,因此我不能使用正则表达式。
解决方案
这是您可能不应该重新发明的功能,但是...如果您不想使用正则表达式,那么您可以尝试这样的功能。
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"
推荐阅读
- python - 随着时间的推移,Django 查询会变慢
- java - 从匿名嵌套内部类更改局部变量
- python - 一类svm python中的异常行为
- reactjs - 'constructor' 和 'super' 上的 React vs Redux 道具
- c++ - 具有 Fluent 接口的 C++ Builder 模式
- javascript - 使用 simpleTones.js 将用户输入作为频率
- ios - 使用 gstreamer 通过网络将 ARFrame CVPixelBuffer 作为字节数组发送时崩溃
- c# - 如何使用反射来获取带有 ref 关键字的方法?
- javascript - 如何在运行另一个函数之前等待 jQuery 切换完成?
- javascript - Javascript 的 CSS Flex 问题,for 循环中的 element.style.display = "none"