Home > Back-end >  comma seperated string to array issue with split() method
comma seperated string to array issue with split() method

Time:10-01

suppose I have a string which has values

var str = 'abc, abc, inc.,  abd'

and I want to split this string to array and problem here is abc, inc and i want it print abc,inc. as one element in array. this whole is a string so that if i use split function it gets separated and we can use by giving var str = 'abc,"abc, inc.",abd' but is there way to split string without this two. We can use the second one but problem is what if I have strings more than 50? Please help me with this i am new to coding.

CodePudding user response:

Here is the simple use of 'split', 'map' and 'trim' (for remove spacing) function that can achieve your gole.

var str = 'abc, abc, inc.,  abd'
str = str.split(',');
var arr = [...new Set(str.map(item=>item.trim()))];
console.log(arr.toString())

CodePudding user response:

First split your string at the commas, then compare the looped value to your target value. If there is a match, use the keys to get the previous value, concatenate the previous and current values together, then use splice to replace the current value with the concatenated value using the keys. Return the newly formatted array.

If this is not what you're looking for, let me know and I can change or remove this answer.

const str = 'abc, abc, inc.,  abd, fgh, jhg,   uiy, inc., yhg,   okj, inc., abc, xyz, inc., mkj, fgh, jhg,   uiy, inc., yhg, abc, inc.,  abd, fgh,yhg,   okj, inc., abc, fjb, inc., lgb '

const evalStr = (str) => {
  // split the string at the commas and create an array o those split values
  const results = str.split(',')
  // loop over the keys & values 
  results.map((a, k) => {
    // compare the value trimmed value 
    a.trim() === 'inc.'
      // we have a match
      // using the keys we get the previous value and current value
      // and concatenate and format the string
      // splice the value starting at the previous value and span 2 values
      // trim white space
      ? results.splice(k - 1, 2, `${results[k-1].trim()},${a.trim()}`) 
      : null
    // if we wish to trim all white space...
    results.splice(k, 1, results[k].trim())  
  })
  return results
}

console.log(evalStr(str))

CodePudding user response:

var str = 'abc,abc,inc,abd';
let fun= str.split(" "); //Gap in Between will help you get the 
console.log(fun);

  • Related