How To Sanitise String Data In Object – Javascript

When we are dealing with user’s input through a form or dealing with input from any other sources. The first scenario we would probably encounter is we would want to receive the data in the format that acceptable to use for our database or matching the structure that of data we would like to receive.

These problems sometimes can be in form of validation or regex matching technique. Nevertheless, sometimes regex do fail and data validation can also fail. This is the optional technique that can be used to deal with string data.

This article will give a small tutorial into how to sanitize string data that is stored in either string variables or was stored inside an object. The solution I’m showing is a very basic in principle. However, can be modified to produce a very complex data validation structure.


function dataSanatize (obj, betweenspc){
/* This function is written by kevinhng86 @ FAI Hosting Solution
 * A copy of this can be found on my blog @
 * Function features: Remove white space between two sides of the string
 *                    Remove the spacing between each word and leave only the amount that is defined.
 * This function will take in two input. 
 * First input can be a string or object. 
 * The second input is how many spaces you would like to have between each word. This must be a numerical value.
 * The second input will set to one if there is not an input value.
    if (betweenspc === undefined) betweenspc = 1; // Set allowable space between each character to if none was set
    var filler = ""; 
    for (i = 0; i < betweenspc; i++){
        filler += " " // Create an empty filler string, this is what allow between each word and will equal to the number defined

    // First we check whether if the input value is an object. if it is the following code block will be executed.
    if (typeof(obj) === "object"){
        // First we run through all the property of an object.
        for (var name in obj){
            if ( typeof(obj[name]) === "object"){
                // If we found the property of an object that happen to be another object.
                // We then call this function on that property.
                obj[name] = dataSanatize(obj[name]);
                } else {
                // For anything else we will use the switch function.
                // The switch function will execute any cases where the condition is true.
                switch (true){
                // The first case is if the object is a string.
                case typeof(obj[name]) === "string":
                    var arridx = 0; // Word count.
                    var str1 = []; // Use to store words.
                    var str2 = []; // Use to store empty spaces between word.
                    var join = ""; // This variable is a temporary string use for joining all the string together after we separate them.
                    obj[name] = obj[name].trim(); // We are trimming off all the space on both side of the string.
                    for ( i = 0; i < obj[name].length; i++){
                        // We are looping through the string character by character.
                        // If the current character is not a space and the previous one is a space and if we are not on the 0 position of the string.
                        // That mean it is a new word so arridx will increase by one.
                        arridx =  obj[name].charAt(i).match(/[^ ]/g) && obj[name].charAt(i - 1).match(/[ ]/g) && i > 0 ? arridx + 1: arridx;

                        // If our word array haven't been defined we will define them here
                        if (str1[arridx] === undefined) str1[arridx] = "";
                        if (str2[arridx] === undefined) str2[arridx] = "";
                        // str1 array will store any character is not a space.
                        str1[arridx] = obj[name].charAt(i).match(/[^ ]/g)? str1[arridx] + obj[name].charAt(i) :  str1[arridx] ;
                        // str2 array will store any character that is a space.
                        str2[arridx] = obj[name].charAt(i).match(/[ ]/g)? str2[arridx] + obj[name].charAt(i) : str2[arridx] ;
                        // Now we loop through each word in our str1 word array to build a new string.
                        // Since we trim off all space on both side of the string.
                        // There will always be more word or equal word to in between space.
                        // Thus we will use str1 as the counter
                    for ( var i in str1){
                        // We will add str1 to str2 through our join string. Word to space between word.
                        // If str2 is not defined then that mean there isn't a space after that word. This is in the event of the last word in the string. If we were to add an undefined value to the last word of the string we would get and undefined word at the end of the string. Therefore we have to declare the variable as an empty string. 
                        // If str2 was defined then we would check how many spaces it has.
                        // If the space in str2 it is less than what we allow. 
                        // We would retain it. Otherwise, we will replace it with the filler variable above.
                        join += str1[i] + ( str2[i] === undefined? "": (str2[i].length < filler.length? str2[i]: filler)   )           
                    // After joining the words together with the in-between spaces, we would set the information into the object.
                    obj[name]= join;
                // If the object is not a string we do nothing, this can be extend.
                } // End switch
            } // End if else from object check
        } // End for loop that read object property
    } // End if block to check object

    else if (typeof(obj) === "string"){
        // If the input object into the function is a string from the begining this code block will execute.
        // This is exactly the same as the above code block.
        var arridx = 0;
        var str1 = [];
        var str2 = [];
        var join = "";
        obj = obj.trim();
        for ( i = 0; i < obj.length; i++){
            arridx =  obj.charAt(i).match(/[^ ]/g) && obj.charAt(i - 1).match(/[ ]/g) && i > 0 ? arridx + 1: arridx;
            if (str1[arridx] === undefined) str1[arridx] = "";
            if (str2[arridx] === undefined) str2[arridx] = "";
            str1[arridx] = obj.charAt(i).match(/[^ ]/g)? str1[arridx] + obj.charAt(i) :  str1[arridx] ;
            str2[arridx] = obj.charAt(i).match(/[ ]/g)? str2[arridx] + obj.charAt(i) : str2[arridx] ;
        for ( var i in str1){
            join += str1[i] + ( str2[i] === undefined? "": (str2[i].length < filler.length? str2[i]: filler)   )           
        obj = join;
    } else { 
        return obj; // If input is not an object nor string return the object 
    return obj; // Return the object
} //End

/* This below remove when in use, this is test cases for you to see if the function work */
test1 = "  abc  abc def   gml       kvn    ";
test2 = {first: "    cad ", second:  "azx", third: "   vvn   5vn     7vn    ", nest1: {count: "  I  am   a giant    big     big     fox", justanumber: 5} }

document.write("Before: <pre>Test1 \n");
document.write(test1 + "\n\n\n");
document.write("Test2: \n");
function z(a){
    for (var n in a){
        if (typeof a[n] === "object") z(a[n]);
        if (typeof a[n] !== "object") document.write(n + " : " + a[n] + "\n");

test1 = dataSanatize(test1, 2);
test2 = dataSanatize(test2);

document.write("After: <pre>Test1 \n");
document.write(test1 + "\n\n");
document.write("Test2: \n");

function z(a){
    for (var n in a){
        if (typeof a[n] === "object") z(a[n]);
        if (typeof a[n] !== "object") document.write(n + " : " + a[n] + "\n");

This post was written by Kevin and was first post @
Original Post Name: "How To Sanitise String Data In Object – Javascript".
Original Post Link:


Random Article You May Like

3 thoughts on “How To Sanitise String Data In Object – Javascript

  1. We’re a gaggle of volunteers and starting a brand new scheme in our community.
    Your website offered us with useful information to work
    on. You have done a formidfable activity and our whole community
    might be thankful to you.

Leave a Reply

Your email address will not be published. Required fields are marked *