I am trying to find a solution for a SQL problem that i think i can solve via JavaScript but cant conceptualize the solution and need some help with it. I have a long string (118.0000000000,102.6666666666,110.6666666666,97.5000000000,82.5000000000,86.6666666666 .... 15000 characters long)
that i need to break into a max string length of 4000 (SQL NVARCHAR(max) limitation) and iterate the strings to a stored proc for further processing. Lets say using the string above i wanted to split the string at 35 character length but not lose data and terminate the new string at the last ',' before the 35th character and build the next string from that point on, so essentially strings would look like this:
118.0000000000,102.6666666666
110.6666666666,97.5000000000
82.5000000000,86.6666666666
I tried to look through all the solutions already presented related to splliting string but have not been able to extract the info that could result in solving my issue here. Appreciate all the help!
If your strings are going to be really long, it might be faster to just work with indexes manually rather than breaking everything into arrays — it's not much less readable. For this you just look ahead to the comma beyond 35 characters with each loop, take the part up to the last comma and reset the position to where the comma was plus 1. If you don't have 35 characters left, just add the last bit and stop.
function splitGroups(str, MAX) {
let res = []
let start = 0
while (start < str.length) {
if (str.length - start <= 35) {
res.push(str.slice(start))
break
}
let c = str.slice(start, str.indexOf(',', start + MAX + 1))
let end = c.lastIndexOf(',')
res.push(c.slice(0, end))
start += end + 1
}
return res
}
let str = "118.0000000000,102.6666666666,110.6666666666,97.5000000000,82.5000000000,86.6666666666"
let groups = splitGroups(str, 35)
console.log(groups)
console.log("lengths", groups.map(s => s.length) )