如何在最后一次出现特定字符之前插入一些东西?
if(语句)在最后一个“<”之前将“再次”插入字符串;
您可以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.
您可以使用 获取指定字符串的最后一次出现lastIndexOf(str)
,它是 anyString
或string
object 的成员函数。然后你可以做这样的事情:
var idx = mystr.lastIndexOf("<");
if (idx > -1)
var outval = mystr.substr(0, idx) + " again" + mystr.substr(idx);