Javascript basics - String Operations

Published On: 2019/09/21

Javascript is a language designed to make websites more dynamic.Though there are so many libraries and frameworks built on javascript, knowing basic javascript functions always helps. In this tutorial we will go through some of the usefull string operations in javascript.

  • String.replace() :: If you need to repalce a part of the string with another string then this is the function to be used. For example, if you need to replace the character ‘/’ in a given string with ‘.’ then you can use replace function to achieve it.

    Note : All codes given below are tested in Jupyter Notebook Here in this example backward slash is replaced with ‘.’

    %%js
    var path="com\\asyncstream\\js\\examples";
    var packagePath = path.replace(/\\/g,'.');
    element.text(packagePath);
        
    

    Result: comasyncstream.js.examples

    Here in this example forward slash is replaced with ‘.’

    %%js
    var path="com/asyncstream/js/examples";
    var packagePath = path.replace(/\//g,'.');
    element.text(packagePath);
        
    

    Result: comasyncstream.js.examples

    If you want to perfom an action after the match then you need to create a function and pass it to the replace method as the second parameter.

    %%js
    function replacer(match, p1, p2, p3, p4,  offset, string) {  
    return [p1, p2, p3, p4].join(' - ');
    };
    // p1 =(\+\d{1}) , p2 = (\d{3,5}) , p3 = (\d{3,9}) , p4 = (\d{4,13})
    var newString = '+15416459870'.replace(/^(\+\d{1})(\d{3,5})(\d{3,9})(\d{4,13})$/, replacer);
    element.text(newString);
        
    

  • String.slice() :: If you want to extract a certain section of a given text and return it as a new string without changing the original text then slice is the method to be used. This method is usefull if you know text to be extracted is located at a specific location in the original text.

    %%js    
    var message = "2019-22-09 I26  Jane Doe is admitted due to Lungenembolie";
    var icdCode = message.slice(11,14);
    element.text(icdCode);
        
    
  • String.split() :: This method splits a string into an array based on a given delimiter. If you are processing a csv record and you want to split the line into an array using a comma delimiter then use the split method.

    %%js
    var line = 'AsyncStream|Tutorial|Article|Privacy|Sitemap';
    var fieldSet = line.split('|');
    element.text(fieldSet);
    // Result : AsyncStream,Tutorial,Article,Privacy,Sitemap
    var path = "com/asyncstream/js/examples";
    var fieldSet1 = path.split('/');
    element.text(fieldSet1);
    // Result : com,asyncstream,js,examples
        
    

  • String.substring() :: One of the mostly used string operation is substring. It is used to extract a part of the given string by providing start index and [end index]. The end index is optional and if it is not provided then it will return the substring from start index to the end of the string. The substring method mostly used along with indexOf and lastIndexOf methods.

    %%js
    var anyString = 'AsyncStream';
    element.text(anyString.substring(0,7));
    // Result : AsyncSt
    element.text(anyString.substring(7));
    // Result : ream
        
    

  • String.repeat() :: With repeat method you can achieve printing of a string n number of times. If you want to create div element 10 times then use repeat as given below

    %%js
    var divElement = "<div></div>";
    var divElements = divElement.repeat(10);
    element.text(divElements);
        
    

  • String.indexOf() :: IndexOf method goes well along with the substring method. If you need to extract a part of the string which begins with a word and ends with same or another then indexOf and lastIndexOf can be used. In the below example we are trying to extract person record from an xml message.

    %%js
    var message = "<data><person><name>John Doe</name><age>27</age><location>berlin</location></person></data>";
    var person = message.substring(message.indexOf("<person>"),message.lastIndexOf("</person>")+"</person>".length);
    element.text(person);
        
    

  • String.match() :: Match method is usefull when you what to extract words or substring based on a regex pattern. This operation will return an array of strings matching to the regex pattern.

    %%js
    var message = "01-01-2019 07:00:56 new vulnarability attack reported from ip 10.7.10.7 and 10.7.10.17";
    var ip = message.match(/(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])/g);    
    element.text(ip);
        
    

comments powered by Disqus