Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert before last 2 char in javascript

Tags:

javascript

How would I insert a % before the last 2 characters in a word?

For example:

var str = "Because";

Output:

Becau%se
like image 670
Rickstar Avatar asked May 03 '11 12:05

Rickstar


People also ask

How to insert a character after every 2 characters in a string?

The algorithm is to group the string into pairs, then join them with the - character. The code is written like this. Firstly, it is split into odd digits and even digits. Then the zip function is used to combine them into an iterable of tuples.

How can I insert a character after every n characters in JavaScript?

To insert a character after every N characters, call the replace() method on the string, passing it the following regular expression - str. replace(/. {2}/g, '$&c') . The replace method will replace every 2 characters with the characters plus the provided replacement.

How do I get the last character in a JavaScript string?

To get the last character of a string, call the charAt() method on the string, passing it the last index as a parameter. For example, str. charAt(str. length - 1) returns a new string containing the last character of the string.

Can we use \n in JavaScript?

The newline character is \n in JavaScript and many other languages. All you need to do is add \n character whenever you require a line break to add a new line to a string.


1 Answers

How about

var str = "Because";
var len = str.length;
var x = str.substring(0, len-2) + "%" + str.substring(len-2);

Hope this helps.

like image 175
Ash Burlaczenko Avatar answered Oct 07 '22 04:10

Ash Burlaczenko