Split a String on 2nd last occurrence of comma in jquery - javascript

I have a string say
var str = "xy,yz,zx,ab,bc,cd";
and I want to split it on the 2nd last occurrence of comma i.e
a = "xy,yz,zx,ab"
b = "bc,cd"
How can I achieve this result?

You can do that by mixing few methods, just like that:
const str = "xy,yz,zx,ab,bc,cd";
const tempArr = str.split(',');
const a = tempArr.slice(0, -2).join(',');
const b = tempArr.slice(-2).join(',');
console.log("a:", a, "b:", b);

Or you can use regex:
var str = "xy,yz,zx,ab,bc,cd";
const [a, b] = str.split(/,(?=[^,]*,[^,]*$)/);
console.log(a);
console.log(b);

Using a regex
var str= "xy,yz,zx,ab,bc,cd"
const parts = [,a,b]=str.match(/(.*),(.*,.*)$/)
console.log(a,b)

counting from back:
let str = "xy,yz,zx,ab,bc,cd";
let idx = str.lastIndexOf(',' , str.lastIndexOf(',')-1);
str.slice(0, idx);
str.slice(idx + 1);

Related

How to extract specific words from a string with some patterns?

I am trying to extract some strings from a word with some pattern like -
"38384-1-page1-2222", "1-22-page33-02", "99-222-frontpage-111"
how will I extract all word between - separately, means first word before - and then second word between - and - and so on...
string = "38384-1-page1-2222";
string.substr(0, string.indexof("-")); //return 38384
But how will I extract 1, page1 and 2222 all the words separately?
The javascript function str.split(separator) split the string by the given separator and it returns an array of all the splited string. REF Here
Here is an example following your question :
var string = "38384-1-page1-2222";
var separator = "-";
var separated = string.split(separator);
var firstString = separated[0]; // will be '38384'
var secondString = separated[1]; // will be '1'
var thirdString = separated[2]; // will be 'page1'
/* And So on ... */
Hope this can help
Use String.prototype.split() to get your string into array
var words = ["38384-1-page1-2222", "1-22-page33-02", "99-222-frontpage-111"];
var resultArray = [];
for (let i = 0; i < words.length;i++) {
let temp = words[i];
resultArray = pushArray(temp.split("-"), resultArray)
}
console.log(resultArray)
function pushArray (inputArray, output) {
for (let i = 0; i < inputArray.length;i++) {
output.push(inputArray[i]);
}
return output;
}
Or simply use Array.prototype.reduce()
var words = ["38384-1-page1-2222", "1-22-page33-02", "99-222-frontpage-111"];
var result = words.reduce((previousValue, currentValue) => previousValue.concat(currentValue.split("-")), [])
console.log(result)
You can use regex /[^-]+/g
const words = ["38384-1-page1-2222", "1-22-page33-02", "99-222-frontpage-111"];
console.log(words.map(v=>v.match(/[^-]+/g)).flat())

Convert a string to array format java script

I hava a string like this "sum 123,645,423,123,432";
How can i convert this string to be like this:
{
“sum”: [ 123,645,423,123,432 ]
}
I try it like this:
var arr = "sum 123,645,423,123,432";
var c = arr.split(',');
console.log(c);
VM3060:1 (5) ["sum 123", "645", "423", "123", "432"]
Thanks!
First, i .split() the string by whitespace, that returns me an array like this ["sum" , "123,645,423,123,432"]
Instead of writing var name = str.split(" ")[0] and var arrString = str.split(" ")[1] i used an destructuring assignment
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
Next step is to split the arrString up by , and then .map() over each element and convert it to an number with Number().
Finally i assign an object to result with a dynamic key [name] and set arr to the dynamic property.
var str = "sum 123,645,423,123,432";
var [name,arrString] = str.split(" ");
var arr = arrString.split(",").map(Number);
let result = {
[name]: arr
}
console.log(result);
//reverse
var [keyname] = Object.keys(result);
var strngArr = arr.join(",");
var str = `${keyname} ${strngArr}`
console.log(str);
const str = "sum 123,645,423,123,432";
const splittedString = str.split(" ");
const key = splittedString[0];
const values = splittedString[1].split(",").map(Number);
const myObject = {
[key]: [...values]
};
console.log(myObject);
There are many ways to dot that,one way to do it using String.prototype.split()
let str = "sum 123,645,423,123,432";
let split_str = str.split(' ');
let expected = {};
expected[split_str[0]] = split_str[1].split(',');
console.log(expected);
This solution is equivalent to #Yohan Dahmani with the use of destructuring array for more legible code.
const str = "sum 123,645,423,123,432";
const [key,numbersStr] = str.split(' ');
const numbersArr = numbersStr.split(',').map(n => parseInt(n, 10));
const result = {[key]: numbersArr};
console.log(result);

How to split a string into an array at a given character (Javascript)

var stringToSplit = "10000.9409.13924.11025.10000._.11025.13225._.9801.12321.12321.11664.";
//Finished result should be:
result == ["10000.", "9409.", "13924.", "11025.", "10000.", "_.", "11025.", "13225.", "_.", "9801.", "12321.", "12321.", "11664."]
After each "." I want to split it and push it into an array.
You split it, and map over. With every iteration you add an . to the end
var stringToSplit = "10000.9409.13924.11025.10000._.11025.13225._.9801.12321.12321.11664.";
let result = stringToSplit.split(".").map(el => el + ".");
console.log(result)
You could match the parts, instead of using split.
var string = "10000.9409.13924.11025.10000._.11025.13225._.9801.12321.12321.11664.",
result = string.match(/[^.]+\./g);
console.log(result);
var stringToSplit = "10000.9409.13924.11025.10000._.11025.13225._.9801.12321.12321.11664.";
var arr = stringToSplit.split(".").map(item => item+".");
console.log(arr);
split the string using . delimiter and then slice to remove the last empty space. Then use map to return the required array of elements
var stringToSplit = "10000.9409.13924.11025.10000._.11025.13225._.9801.12321.12321.11664.";
let newData = stringToSplit.split('.');
let val = newData.slice(0, newData.length - 1).map(item => `${item}.`)
console.log(val)
you could use a lookbehind with .split
var stringToSplit = "10000.9409.13924.11025.10000._.11025.13225._.9801.12321.12321.11664.";
let out = stringToSplit.split(/(?<=\.)/);
console.log(out)

Json from string using regular expression

I have a string like:
const stringVar = ":20:9077f1722efa3632 :12:700 :77E: :27A:2/2 :21A:9077f1722efa3632 :27:1/2 :40A:IRREVOCABLE"
I want to create JSON from above stringVar:
{
":21:" : "9077f1722efa3632",
":12:" : "700",
":27A:": "2/2",
":21A:": "9077f1722efa3632",
":27:" : "1/2",
":40A:": "IRREVOCABLE"
}
So, I was thinking I could split with regular expression (":(any Of char/digit):")
I would make the first part the key and the second part its value.
The regular expression /(:\w+:)(\S+)/ matches the whole key:value pair. You can add the g modifier, and then use it in a loop to get all the matches and put them into the object.
const stringVar = ":20:9077f1722efa3632 :12:700 :77E: :27A:2/2 :21A:9077f1722efa3632 :27:1/2 :40A:IRREVOCABLE"
var regexp = /(:\w+:)(\S+)/g;
var obj = {};
var match;
while (match = regexp.exec(stringVar)) {
obj[match[1]] = match[2];
}
console.log(obj);
If you want to create an array of {key: ":20:", value: "9077f1722efa3632"}, you can modify the code to:
const stringVar = ":20:9077f1722efa3632 :12:700 :77E: :27A:2/2 :21A:9077f1722efa3632 :27:1/2 :40A:IRREVOCABLE"
var regexp = /(:\w+:)(\S+)/g;
var array = [];
var match;
while (match = regexp.exec(stringVar)) {
array.push({key: match[1], value: match[2]});
}
console.log(array);
If the values can contain space, change the regexp to:
/(:\w+:)([^:]+)\s/g
This will match anything not containing : as the value, but not include the last space.
You can achieve the same result without using regex.
const stringVar = ":20:9077f1722efa3632 :12:700 :77E:xxx :27A:2/2 :21A:9077f1722efa3632 :27:1/2 :40A:IRREVOCABLE";
const result = stringVar
.split(' ')
.reduce((ret, current) => {
const pos = current.indexOf(':', 1);
ret[current.substring(0, pos + 1)] = current.substring(pos + 1);
return ret;
}, {});
console.log(result);

Replace last comma separated value by another using regex

I have a string as follows :
var str = "a,b,c,a,e,f";
What I need is replace the last comma separated element by another.
ie, str = "a,b,c,a,e,anystring";
I have done it using split method and adding it to make a new string. But it is not working as expected
What I done as follows :
var str = "a,b,c,d,e,f";
var arr = str.split(',');
var res = str.replace(arr[5], "z");
alert(res);
Is there any regex to help?
You can use replace() with regex /,[^,]+$/ to match the last string
var str = "a,b,c,d,e,old";
var res = str.replace(/,[^,]+$/, ",new");
// or you can just use
// var res = str.replace(/[^,]+$/, "new");
document.write(res);
Or you can just use regex str.replace(/[^,]+$/, "new");
var str = "a,b,c,d,e,old";
var res = str.replace(/[^,]+$/, "new");
document.write(res);
Or using split() , replace the last array value with new string and then join it again using join() method
var str = "a,b,c,d,e,old";
var arr = str.split(',');
arr[arr.length - 1] = 'new';
var res = arr.join(',');
document.write(res);
You could just use a String.substring() of String.lastIndexOf():
function replaceStartingAtLastComma(str, rep){
return str.substring(0, (str.lastIndexOf(',')+1))+rep;
}
console.log(replaceStartingAtLastComma('a,b,c,d,e,f', 'Now this is f'));

Categories

Resources