如何在最后一次出现特定字符之前插入内容?
if(statement)insert"再次"最后一个字符串#34;<";
答案 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
是任何string
或var idx = mystr.lastIndexOf("<");
if (idx > -1)
var outval = mystr.substr(0, idx) + " again" + mystr.substr(idx);
对象的成员函数。然后你可以做这样的事情:
{{1}}