Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs: string manipulation

I have the following node.js code:

   conn.on("data",function(x){
       var responseData=x;
       //sys.puts(responseData);
       sys.puts(responseData.length);

       var f=50;
       var N=responseData.length;
       if(N>f){
         var p=Math.floor(N/f);
         var p_rem=N%f;

         var hash="";
         for(var i=0;i<p;i++){
           hash=DJBHash(responseData.substr(f*i,f));   //this line causes program to exit!
           sys.puts(responseData.substr(f*i,f)+"***"+hash);
         }
       }
       soc.write(x);
    });

But substr doesn't appear to work!

How can I get substrings of a string in node.js?

Many thanks in advance,

like image 993
Eamorr Avatar asked Aug 16 '11 16:08

Eamorr


People also ask

Can you manipulate a string in JavaScript?

In JavaScript, strings are immutable and help us to store text that includes characters, numbers, and Unicode. Also, JavaScript includes many built-in functions for creating and manipulating strings in various ways.

How do you mutate a string in JavaScript?

Strings in JavaScript are immutable. This means that you cannot modify an existing string, you can only create a new string.

How do you declare a string in node?

String literals can be specified using single or double quotes, which are treated identically, or using the backtick character ` .


1 Answers

The variable data is of type Buffer, you would have to create a string with the method toString and then, you will be able to do the substr. Something like that will work :

responseData.toString().substr(1)

For more info consult this link :

http://nodejs.org/docs/v0.4.10/api/buffers.html#buffer.toString

like image 120
fe_lix_ Avatar answered Sep 30 '22 20:09

fe_lix_