0

I have a string i want to split it so that I can extract the name from the particular string.

let str = "CN=John Mcclau - i0c00cu,OU=PET_Associates,OU=Users,OU=PET,DC=officecabs,DC=SAT-PET,Dt=com";

let splitstr= str.substr(3, str.indexOf(' -'))
console.log(splitstr)

Sample str2 = "PN=Coey PT - ljooys4,OU=PET_Associates,OU=Users,OU=PET,DC=officecabs,DC=SAT-PET,Dt=com";

I am doing this way but it displays the " - " too. How can i fix it?

sd_30
  • 576
  • 1
  • 6
  • 21

2 Answers2

1

You can split twice, first on the '=' and taking the second index then on the '-' and taking the first index. Add a trim() and you're good to go

const getName = str => str.split('=')[1].split('-')[0].trim();

let str = "CN=John Mcclau - i0c00cu,OU=PET_Associates,OU=Users,OU=PET,DC=officecabs,DC=SAT-PET,Dt=com";
console.log(getName(str))

str2 = "PN=Coey PT - ljooys4,OU=PET_Associates,OU=Users,OU=PET,DC=officecabs,DC=SAT-PET,Dt=com";
console.log(getName(str2))
Kinglish
  • 23,358
  • 3
  • 22
  • 43
0

If you switch out substr() for slice() it works fine using the same start/end indices

const getName = str => str.slice(3, str.indexOf(' -'));

const str ='CN=John Mcclau - i0c00cu,OU=PET_Associates,OU=Users,OU=PET,DC=officecabs,DC=SAT-PET,Dt=com',
str2 = "PN=Coey PT - ljooys4,OU=PET_Associates,OU=Users,OU=PET,DC=officecabs,DC=SAT-PET,Dt=com";


[str,str2].forEach(s=> console.log(getName(s)))
charlietfl
  • 170,828
  • 13
  • 121
  • 150