insert before last 2 char in javascript - javascript

How would I insert a % 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);

Related

How to increment a string in JavaScript containing leading zeros?

I have string like:
MPG_0023
I want to find something like
MPG_0023 + 1
and I should get
MPG_0024
How to do that in JavaScript? It should take care that if there are no leading zeros, or one leading zero should still work like MPG23 should give MPG24 or MPG023 should give MPG024.
There should be no assumption that there is underscore or leading zeros, the only thing is that first part be any string or even no string and the number part may or may not have leading zeros and it is any kind of number so it should work for 0023 ( return 0024) or for gp031 ( return gp032) etc.
Here's a quick way without using regex.. as long as there's always a single underscore preceding the number and as long as the number is 4 digits, this will work.
var n = 'MPG_0023';
var a = n.split('_');
var r = a[0]+'_'+(("0000"+(++a[1])).substr(-4));
console.log(r);
Or if you do wanna do regex, the underscore won't matter.
var n = "MPG_0099";
var r = n.replace(/(\d+)/, (match)=>("0".repeat(4)+(++match)).substr(-4));
console.log(r);
You can use the regular expressions to make the changes as shown in the following code
var text = "MPG_0023";
var getPart = text.replace ( /[^\d.]/g, '' ); // returns 0023
var num = parseInt(getPart); // returns 23
var newVal = num+1; // returns 24
var reg = new RegExp(num); // create dynamic regexp
var newstring = text.replace ( reg, newVal ); // returns MPG_0024
console.log(num);
console.log(newVal);
console.log(reg);
console.log(newstring);
Using regex along with the function padStart
function add(str, n) {
return str.replace(/(\d+)/, function(match) {
var length = match.length;
var newValue = Number(match) + n;
return newValue.toString(10).padStart(length, "0");
});
}
console.log(add("MPG_023", 101));
console.log(add("MPG_0023", 101));
console.log(add("MPG_0000023", 10001));
console.log(add("MPG_0100023", 10001));
Using regular expression you can do it like this.
var text1 = 'MPG_0023';
var text2 = 'MPG_23';
var regex = /(.*_[0]*)(\d*)/;
var match1 = regex.exec(text1);
var match2 = regex.exec(text2);
var newText1 = match1[1] + (Number(match1[2]) + 1);
var newText2 = match2[1] + (Number(match2[2]) + 1);
console.log(newText1);
console.log(newText2);
Increment and pad the same value (comments inline)
var prefix = "MPG_"
var padDigit = 4; //number of total characters after prefix
var value = "MPG_0023";
console.log("currentValue ", value);
//method for padding
var fnPad = (str, padDigit) => (Array(padDigit + 1).join("0") + str).slice(-padDigit);
//method to get next value
var fnGetNextCounterValue = (value) => {
var num = value.substring(prefix.length); //extract num value
++num; //increment value
return prefix + fnPad(num, padDigit); //prepend prefix after padding
};
console.log( "Next", value = fnGetNextCounterValue(value) );
console.log( "Next", value = fnGetNextCounterValue(value) );
console.log( "Next", value = fnGetNextCounterValue(value) );
One way would e to split the string on the "_" character, increment the number and then add the zeros back to the number.
var testString = "MGP_0023";
var ary = testString.split("_");
var newNumber = Number(ary[1]) + 1;
var result = ary[0] + pad(newNumber);
// helper function to add zeros in front of the number
function pad(number) {
var str = number.toString();
while (str.length < 4) {
str = '0' + str;
}
return str;
}
You could cast to number, increment the value and cast back. Then check if you need leading zeros by looking at the length of the string.
Snippet below:
let str = "MPG_0023",
num = Number(str.substr(4)) + 1,
newStr = String(num);
function addLeading0(str) {
return str.length === 2 ? '00' + str : (str.length === 3 ? '0' + str : str);
}
console.log("MPG_" + addLeading0(newStr));

Javascript nth occurance of a string and extract the sub string upto that

Suppose I have a string like this
var str = 'E2*2001/116*0364*31'
What I want is to find the 3rd occurrence of * in the string and print up to that from starting.
So result would be E2*2001/116*0364*
I have tried something like this jsfiddle.
Corresponding code
var str = 'E2*2001/116*0364*31',
delimiter = '*',
start = 0,
var pos=getPosition(str, *, 3);
alert(pos);
tokens = str.substring(start, getPosition(str,*,3)),
result = tokens;
document.body.innerHTML = result;
function getPosition(str, m, i) {
return str.split(m, i).join(m).length;
}
But unable to get the output.
Can anyone please assist.
Try this.
str.split('*').slice(0,3).join('*') + '*';
var str = 'E2*2001/116*0364*31';
console.log(str.match(/^([^*]*\*){3}/)[0]); // E2*2001/116*0364*
console.log(str.match(/^([^*]*\*){3}/)[0].slice(0, -1)); // E2*2001/116*0364
A solution with String#replace:
var string = 'E2*2001/116*0364*31'.replace(/([^*]+\*){3}/, '');
document.write('<pre>' + JSON.stringify(string, 0, 4) + '</pre>');

JavaScript Split, Split string by last DOT "."

JavaScript Split,
str = '123.2345.34' ,
expected output 123.2345 and 34
Str = 123,23.34.23
expected output 123,23.34 and 23
Goal : JS function to Split a string based on dot(from last) in O(n).
There may be n number of ,.(commas or dots) in string.
In order to split a string matching only the last character like described you need to use regex "lookahead".
This simple example works for your case:
var array = '123.2345.34'.split(/\.(?=[^\.]+$)/);
console.log(array);
Example with destructuring assignment (Ecmascript 2015)
const input = 'jquery.somePlugin.v1.6.3.js';
const [pluginName, fileExtension] = input.split(/\.(?=[^\.]+$)/);
console.log(pluginName, fileExtension);
However using either slice or substring with lastIndexOf also works, and albeit less elegant it's much faster:
var input = 'jquery.somePlugin.v1.6.3.js';
var period = input.lastIndexOf('.');
var pluginName = input.substring(0, period);
var fileExtension = input.substring(period + 1);
console.log(pluginName, fileExtension);
var str = "filename.to.split.pdf"
var arr = str.split("."); // Split the string using dot as separator
var lastVal = arr.pop(); // Get last element
var firstVal = arr.join("."); // Re-join the remaining substrings, using dot as separator
console.log(firstVal + " and " + lastVal); //Printing result
I will try something like bellow
var splitByLastDot = function(text) {
var index = text.lastIndexOf('.');
return [text.slice(0, index), text.slice(index + 1)]
}
console.log(splitByLastDot('123.2345.34'))
console.log(splitByLastDot('123,23.34.23'))
I came up with this:
var str = '123,23.34.23';
var result = str.replace(/\.([^.]+)$/, ':$1').split(':');
document.getElementById('output').innerHTML = JSON.stringify(result);
<div id="output"></div>
let returnFileIndex = str =>
str.split('.').pop();
Try this:
var str = '123.2345.34',
arr = str.split('.'),
output = arr.pop();
str = arr.join('.');
var test = 'filename.....png';
var lastStr = test.lastIndexOf(".");
var str = test.substring(lastStr + 1);
console.log(str);
I'm typically using this code and this works fine for me.
Jquery:
var afterDot = value.substr(value.lastIndexOf('_') + 1);
console.log(afterDot);
Javascript:
var myString = 'asd/f/df/xc/asd/test.jpg'
var parts = myString.split('/');
var answer = parts[parts.length - 1];
console.log(answer);
Note: Replace quoted string to your own need
My own version:
var mySplit;
var str1;
var str2;
$(function(){
mySplit = function(myString){
var lastPoint = myString.lastIndexOf(".");
str1 = myString.substring(0, lastPoint);
str2 = myString.substring(lastPoint + 1);
}
mySplit('123,23.34.23');
console.log(str1);
console.log(str2);
});
Working fiddle: https://jsfiddle.net/robertrozas/no01uya0/
Str = '123,23.34.23';
var a = Str.substring(0, Str.lastIndexOf(".")) //123,23.34
var b = Str.substring(Str.lastIndexOf(".")) //23
Try this solution.
Simple Spilt logic
<script type="text/javascript">
var str = "123,23.34.23";
var str_array = str.split(".");
for (var i=0;i<str_array.length;i++)
{
if (i == (str_array.length-1))
{
alert(str_array[i]);
}
}
</script>
The simplest way is mentioned below, you will get pdf as the output:
var str = "http://somedomain.com/dir/sd/test.pdf";
var ext = str.split('.')[str.split('.').length-1];
Output: pdf

Jquery - Add character after the first character of a string?

Say for example I have
var input = "C\\\\Program Files\\\\Need for Speed";
var output = do_it(input, ':');
Now, I would like output to have the value below :
C:\\\\Program Files\\\\Need for Speed
I need to add a character to the given string just after the first character. How can I achieve that using javascript or jquery ?
Thanks in advance
It's probably not the most efficient way, but I would do something like:
(note: this is just pseudocode)
var output = input[0] + ":" + input.substr(1, input.length);
you can use this like
String.prototype.addAt = function (index, character) {
return this.substr(0, index - 1) + character + this.substr(index-1 + character.length-1);
}
var input = "C\\Program Files\\Need for Speed";
var result = input.addAt(2, ':');
Heres one way of doing it:
Fiddle: http://jsfiddle.net/FjfB9/
var input = "C\\Program Files\\Need for Speed"
var do_it = function(str, char) {
var str = str.split(''),
temp = str.shift()
str.unshift(temp, char)
return str.join('')
}
console.log(do_it(input, ":"))

Replace last index of , with and in jQuery /JavaScript

i want to replace the last index of comma (,)in string with and.
eg . a,b,c with 'a,b and c'
eg q,w,e with q,w and e
DEMO
lastIndexOf finds the last index of the parameter string passed in it.
var x = 'a,b,c';
var pos = x.lastIndexOf(',');
x = x.substring(0,pos)+' and '+x.substring(pos+1);
console.log(x);
you can also use this function
function replace_last_comma_with_and(x) {
var pos = x.lastIndexOf(',');
return x.substring(0, pos) + ' and ' + x.substring(pos + 1);
}
console.log(replace_last_comma_with_and('a,b,c,d'));
An alternative solution using regex:
function replaceLastCommaWith(x, y) {
return x.replace(/,(?=[^,]*$)/, " " + y + " ");
}
console.log(replaceLastCommaWith("a,b,c,d", "and")); //a,b,c and d
console.log(replaceLastCommaWith("a,b,c,d", "or")); //a,b,c or d
This regex should do the job
"a,b,c,d".replace(/(.*),(.*)$/, "$1 and $2")
Try the following
var x= 'a,b,c,d';
x = x.replace(/,([^,]*)$/, " and $1");
Try
var str = 'a,b,c', replacement = ' and ';
str = str.replace(/,([^,]*)$/,replacement+'$1');
alert(str)
Fiddle Demo
A simple loop will help you out
first find the index of all , in your string using,
var str = "a,b,c,d,e";
var indices = [];
for(var i=0; i<str.length;i++) {
if (str[i] === ",") indices.push(i);
}
indices = [1,3,5,7] as it start from 0
len = indices.length()
str[indices[len - 1]] = '.'
This will solve your purpose.

Categories

Resources