How would I insert a %
before the last 2 characters in a word?
For example:
var str = "Because";
Output:
Becau%se
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.
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.
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.
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.
How about
var str = "Because";
var len = str.length;
var x = str.substring(0, len-2) + "%" + str.substring(len-2);
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With