How would I insert a 开发者_JAVA百科%
before the last 2 characters in a word?
For example:
var str = "Because";
Output:
Becau%se
How about
var str = "Because";
var len = str.length;
var x = str.substring(0, len-2) + "%" + str.substring(len-2);
Hope this helps.
Try this
var str = "Because";
var result = str.slice(0, -2) +"%"+str.slice(-2);
Here you go! :)
http://jsfiddle.net/6WNk8/
str.substring(0, str.length - 2) + "%" + str.substring(str.length - 2)
Try using this:
str.substring(0,str.length-2)+"%"+str.substring(str.length-2)
Try
function insert(str, value, position){
return str.substring(0,str.length-position) + value + str.substring(str.length-position);
}
Alternatively...
var str = "Because",
chars = str.split('');
chars.splice(-2, 0, '%');
str = chars.join('');
jsFiddle.
Here's a function I wrote for you to do it!
var MyString = "Because";
// Inserts a string into another string at a given point
function InsertString(OriginalString, InsertingString, Position) {
return OriginalString.substring(0, Position) + InsertingString + OriginalString.substring(Position, OriginalString.length);
}
// You can call this as well if you want it n positions from right
function InsertStringFromRight(OriginalString, InsertingString, CharsFromRight) {
return InsertString(OriginalString, InsertingString, OriginalString.length - CharsFromRight);
}
// Call the function!
var Test1 = InsertString(MyString , "#", 5);
var Test2 = InsertStringFromRight(MyString , "#", 2);
alert(Test1);
alert(Test2);
精彩评论