Home > Software engineering >  JQuery - remove text after character, keep string comma seperated
JQuery - remove text after character, keep string comma seperated

Time:10-27

I have a string:

XXX - Test Text 1, OOO - Test Text 2, Dummy

What I want to do is return this string as:

XXX,OOO,Dummy

So I need to remove everything (and including the dash) but keep the string comma separated. This string could have up to say 10 variables.

CodePudding user response:

This has nothing to do with jQuery, it is just native JavaScript. What you could do is split the string for every comma. Then split every part on the - character and join all the parts together:

parsedString = "XXX - Test Text 1, OOO - Test Text 2, Dummy".split(',')
  .map(part => part.split('-')[0].trim())
  .join(',')

console.log(parsedString);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

1) You can first split the string which will returns an array of strings

str.split(",")

2) use reduce to only get the initial string of all strings in an array that is returned from the 1st step

3) then, join them with ,

const str = "XXX - Test Text 1, OOO - Test Text 2, Dummy";
const result = str
  .split(",")
  .reduce((acc, curr) => {
    let match = curr.match(/[a-z] /i);
    if (match) acc.push(match[0]);
    return acc;
  }, [])
  .join(",");

console.log(result);
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related