在字符串中最后一次出现特定字符之前插入

时间:2013-08-13 02:36:55

标签: javascript string

如何在最后一次出现特定字符之前插入内容?

if(statement)insert"再次"最后一个字符串#34;<";

2 个答案:

答案 0 :(得分:12)

您可以将lastIndexOf()substring()

一起使用
var str="Hello planet earth, you are a great planet.";
var n=str.lastIndexOf("planet");
var str2 = str.substring(0,n)+" again "+str.substring(n);
console.log(str2); // Hello planet earth, you are a great  again planet. 

作为一个很好的功能:

function insertBeforeLastOccurrence(strToSearch, strToFind, strToInsert) {
    var n = strToSearch.lastIndexOf(strToFind);
    if (n < 0) return strToSearch;
    return strToSearch.substring(0,n) + strToInsert + strToSearch.substring(n);    
}

var str ="This <br> is another <br> string <br> example.";
var newStr = insertBeforeLastOccurrence(str, "<", " again");
console.log(newStr); // This <br> is another <br> string  again<br> example.

或作为String方法:

String.prototype.insertBeforeLastOccurrence = function(strToFind, strToInsert) {
    var n = this.lastIndexOf(strToFind);
    if (n < 0) return this.toString();
    return this.substring(0,n) + strToInsert + this.substring(n);    
}

var str ="This <br> is another <br> string <br> example.";
console.log(str.insertBeforeLastOccurrence("<", " again"));
// Output: This <br> is another <br> string  again<br> example.
console.log(str.insertBeforeLastOccurrence("w00t", " again")); // wont find
// Output: This <br> is another <br> string <br> example.

答案 1 :(得分:3)

您可以使用lastIndexOf(str)获取指定字符串的最后一次出现,String是任何stringvar idx = mystr.lastIndexOf("<"); if (idx > -1) var outval = mystr.substr(0, idx) + " again" + mystr.substr(idx); 对象的成员函数。然后你可以做这样的事情:

{{1}}