Search code examples
javascriptrestsharepoint-2010csom

Rules for the list name used with ListData.svc in sharepoint 2010


I want to fetch contents of sharepoint 2010 list through rest API. But name of my lists are really wired (They contain all sorts of special characters like: "," , "?" , "-" , "/" , "(" etc) and i can't change them.

Example : 1) Claim Reminder, GT 2) z - Det - andt 3) z - Pens - afregng fra 3860 4) z - Grup/liv moget? (Kred)

I tried the following rest api url :

http://domain/_vti_bin/listdata.svc/"+encodeURIComponent(listName)+"/

When the listName is simple ie. without special characters and empty spaces,I get the output. But when it contains the above special characters, it gives error.

I consulted the following url : https://blogs.msdn.microsoft.com/laurieatkinson/2014/06/19/rules-for-the-list-name-used-with-listdata-svc/

but only got resolution for apostrophe but not the other special characters.

Kindly help.


Solution

  • You can use the following JavaScript function to convert the list name.

    function  convertListName(listName){
        var newListName="";
        var array=listName.split(/[.\-_, '?()$%^!@~+`|={}<>\[\]/]/g);   
        for(var i=0;i<array.length;i++){
            newListName+=array[i].charAt(0).toUpperCase() + array[i].slice(1)
        }
        if(!isNaN(newListName.charAt(0))){
            newListName="c_"+newListName;
        }
        return newListName;
    }
    

    If you use the C# code, we can use the Microsoft.SharePoint.Linq.Util.GetFriendlyName method.

    internal static string GetFriendlyName(string name) 
    { 
        string[] array = Regex.Split(name, "[^\\p{Lu}\\p{Ll}\\p{Lt}\\p{Lm}\\p{Lo}\\p{Nl}\\p{Mn}\\p{Mc}\\p{Nd}\\p{Pc}\\p{Cf}]", RegexOptions.Compiled); 
        for (int i = 0; i < array.Length; i++) 
        { 
            if (!string.IsNullOrEmpty(array[i]) && char.IsLower(array[i], 0)) 
            { 
                array[i] = char.ToUpper(array[i][0], CultureInfo.InvariantCulture) + ((array[i].Length > 0) ? array[i].Substring(1) : string.Empty); 
            } 
        } 
        name = string.Join(string.Empty, array); 
        if (string.IsNullOrEmpty(name)) 
        { 
            throw new InvalidOperationException(Resources.GetString("CannotConvertNameToValidIdentifier", new object[] 
            { 
                name 
            })); 
        } 
        if (Regex.IsMatch(name[0].ToString(), "[^\\p{Lu}\\p{Ll}\\p{Lt}\\p{Lm}\\p{Lo}\\p{Nl}]", RegexOptions.Compiled)) 
        { 
            name = "c_" + name;
        } 
        if (name.Length > 128) 
        { 
            name = name.Substring(0, 128); 
        } 
        return name; 
    }