-1

这就是我想要做的。老实说,我什至不知道从哪里开始。

var text1 = 'ThE foX iS brown',

        text2 = 'the fox is brown the fox is brown THE FOX IS BROWN',

        index = text2.toLowerCase().indexOf(text1.toLowerCase()),

        output = 'do something with substring?';

    alert(index);

“text2”应更改为: The fox is brown the fox is brown THE FOX IS BROWN

    var text1 = 'ThE foX iS brown the FOX is BrO',

        text2 = 'the fox is brown the fox is brown THE FOX IS BROWN',

        index = text2.toLowerCase().indexOf(text1.toLowerCase()),

        output = 'do something with substring?';

    alert(index);

在这种情况下,“text2”应更改为:狐狸是棕色的狐狸是棕色的狐狸是棕色的

我想也许我应该首先尝试在“text2”中找到字符串“text1”的“第一次”出现,但它似乎不起作用?我想在那之后我可以使用substring?或者也许有更简单的方法来做到这一点?我不确定。任何帮助将非常感激。谢谢你。

4

2 回答 2

1

您正在寻找的是用 替换第一次出现的子字符串,text1忽略大小写。text2text1

您可以为此构建一个正则表达式,使用“i”gnore-case 标志。

假设您不知道 的内容text1,则必须转义一些由正则表达式解释的特殊字符。一旦你有了你的正则表达式,你就可以使用replace

这是一个例子:

// Function to escape Regular Expressions special characters.
// From: http://stackoverflow.com/questions/3115150/how-to-escape-regular-expression-special-characters-using-javascript
RegExp.escape = function(text) {
  return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
};

var text1 = 'ThE foX iS brown';
var text2 = 'the fox is brown the fox is brown THE FOX IS BROWN';

// Create the Regular Expression with the "i"gnore-case flag
var re = new RegExp(RegExp.escape(text1), "i");

var output = text2.replace(re, text1);
// output -> ThE foX iS brown the fox is brown THE FOX IS BROWN

是一个工作小提琴

于 2013-06-19T21:11:50.853 回答
1

看起来你只是想用 text1 替换字符串的第一部分。

你可以试试这个。

int text1Size = text1.length;
output = text1 + text2.substring(text1Size);
于 2013-06-19T20:53:22.403 回答