Replace last index of , with and in jQuery /JavaScript - 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.

Related

Match numbers in a String only once

I´ve got this code, but now I´m trying to match numbers only once.
var text = "91308543 v1_Printer 91308543 v2 91503362 v1_Printer";
var regex = /9\d{7}/g;
var result = text.match(regex);
var pos0 = result[0];
var pos1 = result[1];
var pos2 = result[2];
return(pos0 + " " + pos1 + " " + pos2);
Result is: 91308543 91308543 91503362
Result I want: 91308543 91503362
It is possible to add something to my regex so it doesn´t show duplicate values?
I prefer not to use Arrays because in that case I need to use Native Arrays...
I also have a second question, it is possible to create the variables "pos0", "pos1"... automatically?
Thank you!
The regex you are looking for is
(9\d{7})\b(?!.*\1\b)
It uses negative lookahead. See demo.
The second point is achievable through eval:
var result = text.match(regex);
for (var i = 0; i < result.length; i++){
eval('var pos' + i + ' = "' + result[i] + '"');
}
but this does not help you with the return statement.
You should just use:
return(result.join(" "));
You can filter out the duplicates after matching, and use a destructuring assingment to assign to individual variables:
let text = "91308543 v1_Printer 91308543 v2 91503362 v1_Printer";
let regex = /9\d{7}/g;
let [pos0, pos1, pos2] = text.match(regex).filter((v, i, a) => a.indexOf(v) === i);
console.log(pos0);
console.log(pos1);
console.log(pos2);
Try this pattern (9\d{7})(?!.*\1) negative lookahead .Its not allow the duplicate
Demo regex
For more reference
var text = "91308543 v1_Printer 91308543 v2 91503362 v1_Printer";
var regex = /(9\d{7})(?!.*\1)/g;
var result = text.match(regex);
console.log(result)

Dynamically change element name in jquery

The following is my element id and I want to update it dynamically.
invoice[46][ap_details][4][ap_header_id]
I want to update only second number, i.e. [4], like this:
invoice[46][ap_details][5][ap_header_id]
I am using below code which is updating both the values.
var strNewName = $(this).attr('name').replace(/\[\d+\]/g, function(strName) {
strName = strName.replace(/[\[\]']+/g, '');
var intNumber = parseInt(strName) + 1;
return '[' + intNumber + ']';
});
Any help would be appreciated.
var strName = "invoice[46][ap_details][4][ap_header_id]";
var parts = strName.split('[');
parts[3] = parts[3].replace(/^\d+/, n => +n + 1);
var strNewName = parts.join('[');
console.log(strNewName);
If you don't want to use arrow functions replace this line:
parts[3] = parts[3].replace(/^\d+/, n => +n + 1);
with this:
parts[3] = parts[3].replace(/^\d+/, function(n) { return +n + 1; });
Explanation:
split will return an array like this:
[
"invoice",
"46]", // parts[1] to change this
"ap_details]",
"4]", // parts[3] to change this (and so on, you do the math)
"ap_header_id]"
]
The /^\d+/ will match any number at the begining (no need for the g modifier).
Replace with +n + 1 not n + 1 because n is a string, you have to force the interpretter to use it as a number or otherwise this "4" + 1 will result to this "41".
Then after you change what you want, join the parts using join with the same character you used for splitting ([).
Using this regex /((\w)+)(\[\d+\])(\[(\w)+\])(\[\d+\])(\[(\w)+\])/gi you can construct the string back and change your integer.
var match = /((\w)+)(\[\d+\])(\[(\w)+\])(\[\d+\])(\[(\w)+\])/gi.exec(youString);
//group 6 is your digit.
var newId = parseInt(match[6].replace("\[\]", "")) + 1;
var newString = match[1] + match[3] + match[4] + "[" + newId + "]" + match[7];
Here is a fiddle with the answer https://jsfiddle.net/gzfud9vc/
Maybe dont use regex to build your element id. You can do its as follows as well:
var id = 5
var name = "invoice[46][ap_details][";
name += id;
name += "][ap_header_id]";
var toReplace = "invoice[46][ap_details][~~id~~][ap_header_id]"
var replaced = toReplace.replace(/~~id~~/g, id);
console.log(name);
console.log(replaced);

Regex two string variables

Say I have two string variables:
a = 'LOVE';
b = '....';
How do I use regex (or whatever else is fastest) to combine a + b to make:
c = 'L.O.V.E.';
In my case, both strings are 4 characters long, always, and the second string is not a fixed character, I just made it a dot to make it look clearer on screen.
You can simply loop through the longer string and in each iteration append one character from both strings to your resulting string. I don't think you need any regular expression there:
a = 'LOVE';
b = '....';
var combinedString = '';
var largerLength = Math.max( a.length, b.length );
for( var i = 0; i < largerLength; i++ )
{
combinedString += a.charAt(i) + b.charAt(i);
}//for()
console.log( combinedString );
The above code will work for strings of any length. In case, you know beforehand that both strings are exactly 4 characters long, I think the fastest and most efficient way would be:
a = 'LOVE';
b = '....';
var combinedString = a.charAt[0] + b.charAt[0] + a.charAt[1] + b.charAt[1] + a.charAt[2] + b.charAt[2] + a.charAt[3] + b.charAt[3];
console.log( combinedString );
You could use Array#reduce for it
var a = 'LOVE',
b = '....';
c = a.split('').reduce(function (r, v, i) {
return r + v + b[i];
}, '');
console.log(c);
How to combine a + b via regex:
var a = "LOVE", b = "....";
var result = a.replace(/./g, (match, i) => match + b[i]);
console.log(result);
There is no need of regex for your problem. You can simply do it with the help of for loop
a = 'LOVE';
b = '....';
var result = '';
var length = Math.max( a.length, b.length );
for( var i = 0; i <+ length-1; i++ )
{
result = result + a.charAt(i);
result = result + b.charAt(i);
}
alert("Result of combined string is :"+ result);
You can use array functions on array likes (in this example strings) to iterate over it's items.
var a = 'LOVE',
b = '....',
c = Array.prototype.map
.call(a, (v, i) => v + b[i]).join('');
console.log(c);
If your second string is always composed of dots, instead of repeating same characters in string, try something like this:
Using Delimiter
var a = "LOVE";
var delimeter = ".";
var result = a.split("").join(delimeter) + delimeter;
console.log(result)
Array convert + manual concatenation
As an alternate to string.charAt, you can try something like this:
Note: you should do a1[i] || "" for cases where value can be undefined. Also you should use .toString() to avoid cases where both values are numeric and result will be addition instead of concatenation.
var a = 'LOVE';
var b = '....';
var c = ",,,,,,,,,,,";
function mergeStr(a, b) {
var a1 = a.split("");
var b1 = b.split("");
var len = Math.max(a.length, b.length)
var r = "";
for (var i = 0; i < len; i++) {
r += (a1[i] || "").toString() + (b1[i] || "").toString();
}
return r;
}
console.log(mergeStr(a,b))
console.log(mergeStr(a,c))

the first letter then every second letter or space of the original string

Ask the user to enter a string.
Print a new string composed as follows:
the first letter, then every other letter(every second letter) or space of the original string.
presented the example below (Eg 'Airplane' => 'Arln' ; 'Good Day' => 'Go a')
var str=prompt("Insert string");
for(var i=1;i<=str.length;i=i+2){
var str1=str.push[i];
var newStr=str.splice[str[i],str.length-1];
}
console.log(newStr);
Based from your code, try:
var str = prompt("Insert string");
var newStr = '';
for(var i = 0; i < str.length; i = i + 2){
newStr += str[i];
}
console.log(newStr);
You can do it in this way.Use Array#filter
var str = 'Airplane';
str.split('').filter(function(val,key){
return key%2==0;
}).join('');
A variable declared inside for cycle will be available only in that context, so console.log(newStr) will print undefined. To be able to "save your work" you should define some variable outside of for cycle.
Here is an example:
var str=prompt("Insert string");
var newStr = str[0];
for(var i=1; i<=str.length+2; i=i+2){
newStr = newStr + str[i];
}
console.log(newStr);
You can do something like
var str = "Good Day";
var res = str.split("").filter(function(str, index) {
return index % 2 == 0;
}).join('');
Example https://jsfiddle.net/mo44dhyq/
.split('') - It will split the string into an array by each letter and return the array (documentation).
.filter(function(str, index) {return index % 2 == 0; }) - This will iterate over the elements in the array (Returned from the split() function) and return only the even indexes (documentation).
.join('') - Join the results of the filter() function into a new string (documentation).
The solution using String.split and Array.forEach functions:
var str = 'Airplane',
arr = str.split(""), cutted = "";
arr.forEach((v, k) => (k % 2 !== 0) || (cutted += v)); // ES6 arrow function expression
console.log(cutted); // "Arln"
Here is a simple code:
var str = prompt("Insert string"),
str = str.split(''),
str1 = " ",
len = str.length;
for(var i=0; i < len ;i++){
var newStr=str.splice(0,1);
if((i%2) === 0) {
str1 = str1 + newStr[0];
}
}
console.log(str1);
I hope this should the problem.
First convert the string into an array of characters using split, then iterate through the array. Remember splice returns an array and affects the original array.
You could use a regular expression and an apropriate replace.
Edit: Proposal with spaces.
document.write('<pre>' + 'Airplane'.replace(/(.)./g, '$1') + '</pre>');
document.write('<pre>' + 'Good Day'.replace(/(.)./g, '$1') + '</pre>');
document.write('<pre>' + 'Airplane'.replace(/(.)./g, '$1 ') + '</pre>');
document.write('<pre>' + 'Good Day'.replace(/(.)./g, '$1 ') + '</pre>');

insert before last 2 char in 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);

Categories

Resources