首页 > 解决方案 > 将一个词转换成另一个词

问题描述

如何将一个单词传递到另一个单词中的特定位置?假设我有一个名为“apartment”的字符串,我想在字符串“apartment”中的 3 个字母之后传递另一个名为“blue”的字符串。前任。“公寓”

标签: javascript

解决方案


您可以创建一个可重用的函数,该函数将从3字符中分割给定的单词并相应地添加新单词。

function replacement(word, index){
  return word.slice(0,index)+'blue'+word.slice(3);
}

var res = replacement('appartment', 3);
console.log(res);
res = replacement('other', 3);
console.log(res);

您还可以使用以下substring方法:

function replacement(word, index){
  return word.substr(0,index)+'blue'+word.substr(3, word.length-1);
}

var res = replacement('appartment', 3);
console.log(res);
res = replacement('other', 3);
console.log(res);


推荐阅读