I have a string 123456789.
My aim is to get 1236789 after deleting 45.
I used slice method to delete the string 45.
var x = 123456789;
res = x.slice(4, 5); //my output is 45
I need the output to be 1236789
Any help would be appreciated.
Slice before, slice after, and concatenate the resulting strings or replace the 45 with an empty string:
var x = "123456789"
var res1 = x.slice(0, 3) + x.slice(5)
console.log(res1)
var res2 = x.replace('45', '')
console.log(res2)
try replace/2.
"123456789".replace("45", "") /** 1236789 */
Or, if your input is an integer and you need and integer as an outcome,
var a = 123456789;
parseInt(a.toString().replace("45", ""))
You can so this:
var x = "123456789";
var result = x.substr(0, 3) + x.substr(5);
console.log(result)
Related
Is there a way to replace the last item in array with one line of code?
What I receive:
return "my.long.string";
What I want:
return "my.long.output";
Code so far:
var value = "my.long.string";
var newValue = value.split(".").pop().join(".") + "output";
Error:
SyntaxError: Unexpected string
Update:
Nina answered it. I also had a case where I need to insert a value at the end of the string (add in a name to a file path). It's the same as above but replaces everything right before the last dot.
var value = "my.long.string";
var result = value.split(".").slice(0, -1).join(".") + "_stats." + "output";
You could slice the array and concat the last string. Array#slice takes negative values for offsets from the end of the array.
var value = "my.long.string";
value = value.split('.').slice(0, -1).concat('output').join('.');
console.log(value);
You also don't have to convert it into an array. You could use lastIndexOf like so:
const value = "my.long.string";
console.log(`${value.substring(0,value.lastIndexOf('.'))}.output`);
You could use the regex (.*\.).* to capture everything up until the final . and replace the last part with the new string (Regex demo). $1 gets the string from the capture group
let str = "my.long.string"
let newStr = str.replace(/(.*\.).*/, `$1output`);
console.log(newStr)
var value = "my.long.string";
var newValue = value.split('.').filter((val, idx, arr) => {
return idx < arr.length - 1
}).concat('output').join('.');
First solution
var value = "my.long.string";
var newValue = value.split('.').splice(0, value.match(/\./g).length).concat('output').join('.');
console.log(newValue);
Second solution (shorter)
var value = "my.long.string";
var newValue = value.split('.').fill('output', value.match(/\./g).length).join('.');
console.log(newValue);
following code you can try.
var value = "my.long.string";
var newValue = value.replace(new RegExp(value.split(".").pop() + '$'), "output");
var value = "my.long.string";
var r = value.split(".").splice(-1, 1).join(".");
var result = r.".output";
hello I have values like this
1-10
2-3
901-321
I want to get the reverse values for example like this
10-1
3-2
321-901
I have tried this
var str = "1-18";
var newString = "";
for (var i = str.length - 1; i >= 0; i--) {
newString += str[i];
}
return newString;
But it gives me 81-1
Instead, use String.split(), Arrary.reverse() and Arrary.join():
var str = '901-321';
var strArray = str.split('-'); // ['901', '321']
var strArrayReversed = strArray.reverse(); // ['321', '901']
var result = strArrayReversed.join('-'); // '321-901'
console.log('result = ', result);
// You can do all these steps above in one go as:
var result2 = str.split('-')
.reverse()
.join('-');
console.log('result2 = ', result2);
MDN Docs:
String.prototype.split()
Array.prototype.reverse()
Array.prototype.join()
Can split on the - to create array , reverse the array and join it back into string
var str = "1-18",
newStr = str.split('-').reverse().join('-');
console.log(newStr)
a = "12-5"
console.log(a.split('-').reverse().join('-'))
You can use the split method to divide the string in two, and then use the second part before the first, like this:
var str = "1-18";
var l = str.split("-");
return l[1] + "-" + l[0];
You could replace the string by swapping the values.
var string = '901-321';
console.log(string.replace(/(.+)-(.+)/, '$2-$1'));
So i have this string
first €999, second €111
Im trying to make an array that looks like this (numbers after every €)
999,111
Edit:
Yes i have tried to split it but wont work. i tried to look it up on google and found something with indexof but that only returned the number of the last €.
rowData[2].split('€').map(Number);
parseInt(rowData[2].replace(/[^0-9\.]/g, ''), 10);
split(rowData[2].indexOf("€") + 1);
The numbers are variable.
var input ="first €999, second €111";
var output=[];
var arr = input.split(",");
for(var i=0;i<arr.length;i++)
{
output.push(parseInt(arr[i]));
}
var output_string = output.stingify();
console.log(output); //Output Array
console.log(output_string); //Output String
If the numbers will always be of 3 digits in length, you can do this. If not, you need to specify a bit more.
var string = "€999, second €111";
var temp = [];
var digitArray = [];
temp = string.split(",");
for(var i=0;i<temp.length,i++){
digitArray.push(temp[i].substring(temp[i].indexOf("€"),3));
}
//digitArray now contains [999,111];
Edit, based on your requirement of variable digit lengths
var string = "€999, second €111, third €32342";
var temp = [];
var digitArray = [];
temp = string.split(",");
for(var i=0;i<temp.length,i++){
digitArray.push(temp[i].replace(/^\D+/g, '')); //Replace all non digits with empty.
}
//digitArray now contains [999,111,32342]
Not sure how valid is this approach, but I'm unable to split the string into 2 when there are repeated characters.
var match = 's';
var str = "message";
var res = str.split(match, 2);
For instance i tried to use split() on the string "message", it results into:
me,""
So i did this:
res = str.split(match, 3);
so now it resulted into:
me,,age
but as you can see im still missing the second 's' in the "message" string. what im trying to get is I'm passing a matched character (in above case var match which is dynamically generated) to the split() and splitting into 2. I was hoping to get something this:
res = me,,sage
is that possible using split() or is there a better method to achieve this?
P.S: in fiddle i've given another string eg: (string = "shadow") which works fine.
Fails only when there are repeated letters in the string!
fiddle: https://jsfiddle.net/ukeeq656/
EDIT::::::::::::
Thanks everyone for helping me out on this...and so sorry for last min update on the input, i just realized that var match; could be a word too, as in var match = 'force'; and not just var match ='s'; where the string is "forceProduct", so when my match is more than just a letter, this approach works: str.split(match, 2);, but str.indexOf(match); doesnt obviously... could there be an approach to split: "","Product". My extreme apologies for not mentioning this earlier.any help on this would be appreciated!!
eg fiddle:
https://jsfiddle.net/ukeeq656/3/
I don't think split() is the correct way to do this.
Please see below:
var match = 's';
var str = "message";
var index = str.indexOf(match);
var res =[];
res[0] = str.substring(0, index);
res[1] = " ";
res[2] = str.substring(index + 1);
console.log(res);
I'm not sure what your end goal is but I think this gets you what you want.
var match = 's';
var str = "message";
var index = str.indexOf(match);
var res = str.substring(0, index) + ',' + str.substring(index + 1);
alert(res); // me,sage
You could write a function to do this;
function newSplit(str, match) {
var num = str.indexOf(match);
var res = [];
res.push(str.substring(0, num));
//res.push(str.substring(num + 1, str.length)); // this line has been modified
res.push(str.substring(num + match.length, str.length));
return res;
}
var match = 'force';
var str = 'forceProduct';
console.log(newSplit(str, match));
This is what you want?
I have an array of string like below:
var array =[];
array.push("Complex12");
array.push("NumberCar1");
array.push("Protect5");
I want to split the string and number of each item.
var Id = parseInt(array[0].match(/\d/g));
var type = array[0].replace(/\d+/g, '');
But I only get Id = 1(I want 12) and type = "Complex", where am I wrong?
thanks
I think you just missed + in first regexp
var Id = parseInt(array[0].match(/\d+/g));
Do it in one pattern with capture groups:
var mystr = "Complex12";
if (m = mystr.match(/^([a-z]+)([0-9]+)$/i)) {
var type = m[1];
var id = m[2];
}