Question

I have a list field (str) but it contains a list of items. Problem is, it's a field for legacy categories, and some use "," some use "|" while others use ";".

Currently, the following works on all fields using ";"

var cats = Srch.U.getArray(ctx.CurrentItem.Categories);
console.log(cats);

Looks like:

["Cat1", "Cat2", "Cat3"]

Any fields using "|" look like

["Cat1|Cat2|Cat3"]

I've tried appending a delimiter parameter to the getArray method but it does nothing.

var cats = Srch.U.getArray(ctx.CurrentItem.Categories,"|");

or

var cats = Srch.U.getArray(ctx.CurrentItem.Categories,",");
Was it helpful?

Solution

Srch.U.getArray - https://msdn.microsoft.com/en-us/library/office/dn768314.aspx

Execute Srch.U.getArray.toString() in the F12 Dev Console to read the function definition:

function (a) {
    if (Srch.U.e(a)) return a;  // Null or Empty string
    if (a.indexOf(",#") >= 0) return a.split(",#");
    else if (a.indexOf(" | ") >= 0) return Srch.ValueInfo.Renderers.parseUserFieldValue(a).split(",");
    return a.split(";")
}

Srch.U.getArray(a) only splits on one separator, based on the syntax it finds in the String

There is no second parameter,
and defaults to ; if the string is not a SharePoint Lookup or SharePoint Person string

split the string with multiple separators

So instead of using that Microsoft wrapper function, write your own code..
it's shorter, faster, and more versatile

"Cat1,Cat2|Cat3;Cat4".split(/[,|;]/)

will split (using a Regular Expression) on any of the three separators , | ;
(ofcourse these should not be regular characters in your item values then)

►["Cat1", "Cat2", "Cat3", "Cat4"]

It is not uncommon to have whitespace in data

"Cat1, Cat2| Cat3 ; Cat4".split(/\s*[,|;]\s*/)

removes whitespace before and after an item

►["Cat1", "Cat2", "Cat3", "Cat4"]
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top