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

前端之家收集整理的这篇文章主要介绍了javascript – 在字符串中最后一次出现特定字符之前插入前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如何在特定角色的最后一次出现之前插入一些东西?

if(statement)在最后一个“<”之前将“again”插入字符串;

解决方法

您可以将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.

猜你在找的JavaScript相关文章