You must Sign In to post a response.
  • Category: JQuery

    Add commas to a string in jquery

    Hi,

    I want to add commas to a string.

    ie var strname="YYYYNN"

    i need strname should be "Y,Y,Y,Y,N,N"

    how it is possible.


    Regards

    Baiju
  • #764659
    Hi baiju,
    try this:
    <asp:Button runat="server" ID="demoButton" Text="Replace" OnClientClick="javascript:return commaSeparatedString('YYYYNN');"/>

    <script type="text/javascript">
    function commaSeparatedString(szInputString)
    {
    while (/(\w+)(\w{1})/.test(szInputString.toString()))
    {
    szInputString = szInputString.toString().replace(/(\w+)(\w{1})/, '$1' + ',' + '$2');
    }
    alert(szInputString);//Y,Y,Y,Y,N,N
    }
    </script>
    Hope it helps.
    Regards,
    Shashikant Gurav
    shashikantgurav22@gmail.com

  • #764683
    its simple, just iterate loop on each character in string and then add comma in it
    see below snippet
    var szStr;
    for (var i = 0, len = str.length; i < len; i++)
    {
    szStr = szStr + "," + str[i];
    }
    OR
    var text = 'test';

    for(var x = 0, c=''; c = text.charAt(x); x++){
    szStr = szStr + "," + c;
    }

    Thanks
    Koolprasd2003
    Editor, DotNetSpider MVM
    Microsoft MVP 2014 [ASP.NET/IIS]


Sign In to post your comments