Javascript 如果字符串重复,则替换子字符串效果不佳

Javascript replace substring doesn't work well if the string repeats

我有一个关于 substring/substr/slice 的非常简单的问题。我的代码非常复杂,所以我不会在这里 post,但这里是问题的简化版本:

例如如何将 text.substring(5, 10) 更改为 "Something"?

text = "HelloHello";

如果我尝试

text = text.replace(text.substring(5,10), "Something");

结果会是"SomethingHello",因为text.substring(0, 5)也是"Hello",但是我想得到"HelloSomething"

它对 slice() 和 substr() 也不起作用,你能告诉我一个解决方案吗?

根据下面的评论,我编写了函数 replacePartOfText()

此函数将两个索引(开始,结束)之间的所有文本替换为单词

text = "HelloHello"

function replacePartOfText(text, start, end, word) {
  result = text.substring(0, start) + word + text.substring(end, text.length)

  return result
}

text = replacePartOfText(text, 5, 10, "Something")

console.log(text) // "HelloSomething"

var text = "HelloHelloMahamadali.It is working now.";
var textbefore = text.substring(0,5);
var textafter = text.substring(5,text.length);
var texttoreplace = "Hello";
text = textbefore + textafter.replace(texttoreplace, "Something");
alert(text);

请使用以上一种逻辑,希望对您有所帮助。谢谢。欢迎评论。

首先,让它工作:

为了满足这个需求:

"how to replace the string between the characters text[a] and text[b]"

function replaceStringPortion(text, start, end, replacement, trim) {
  text = !!trim ? text.trim() : text;
  var fragments = [
    text.substr(0, start),
    text.substr(start, end - start + 1),
    text.substr(end + 1, text.length)
  ];
  fragments[1] = replacement;
  return fragments.join('');
}

但是,为了满足您描述的需要(替换之后部分ab之间的文本):

function replaceAfterStringPortion(text, start, end, replacement, trim) {
  text = !!trim ? text.trim() : text;
  var fragments = [
    text.substr(0, start),
    text.substr(start, end - start + 1),
    text.substr(end + 1, text.length)
  ];
  fragments[2] = replacement;
  return fragments.join('');
}

其次,.substr().replace() 工作得很好。原因如下:

如果嵌套表达式命令,可能会更清楚:

text = text.replace(
    text.substring(5,10), // Returns "Hello"
  "Something"
);

所以你在做什么,顺序是:

  1. text.substring(5,10) 其中 returns "Hello"
  2. text.replace("Hello", "Something"); 正如预期的那样,return "SomethingHello"

这是预期的,因为 .replace() 替换了您传递的字符串或模式的第一次出现:

str.replace(regexp|substr, newSubStr|function)

...

substr (pattern)

A String that is to be replaced by newSubStr. It is treated as a verbatim string and is not interpreted as a regular expression. Only the first occurrence will be replaced.

为什么不使用 splice 而不是所有这些令人费解的解决方案?

var chars = "HelloHelloHello Hello HelloHello".split( "" );

chars.splice( 16, 5, "Something" );

alert( chars.join( "" ) );

清晰的功能性、可读性和可维护性将永远是赢家,这是显而易见的。