Search code examples
javascriptstringsubstringstring-parsing

How can I detect and parse from one of these string formats in JavaScript?


I am writing a JavaScript function (no jQuery), which will receive a string with one of the following formats:

  1. [Blah] [Read this] [Blah] [Optional blah]
  2. [Blah] Read this [Blah] Optional blah

I want to pick the "Read this" string out of the rest. The "Optional blah" bits may or may not be present (along with the accompanying square brackets in the first case), but they shouldn't matter. Any ideas on how to write a function that does this?


Solution

  • Reg Exp will do the job :

    var a = "[Blah] [Read this] [Blah] [Optional blah]";
    var b = "[Blah] Read this [Blah] Optional blah";
    var text1 = a.match(/\[[^\]]+\]\s*\[*([^\]\[]+)\]*\s*\[[^\]]+\]\s*(\[*[^\]]+\]*)*/)[1].trim();
    var text2 = b.match(/\[[^\]]+\]\s*\[*([^\]\[]+)\]*\s*\[[^\]]+\]\s*(\[*[^\]]+\]*)/)[1].trim();
    
    console.log(text1); // "Read this"
    console.log(text2); // "Read this"
    

    Edit1 If you want to know which format you have :

    var a = "[Blah] [Read this] [Blah] [Optional blah]";
    var b = "[Blah] Read this [Blah] Optional blah";
    var text1 = a.match(/\[[^\]]+\]\s*(\[*([^\]\[]+)\]*)\s*\[[^\]]+\]\s*(\[*[^\]]+\]*)*/);
    var text2 = b.match(/\[[^\]]+\]\s*(\[*([^\]\[]+)\]*)\s*\[[^\]]+\]\s*(\[*[^\]]+\]*)/);
    var text1_value = text1[2].trim();
    var text2_value = text2[2].trim();
    var text1_is_A_format = (/\[[^\]]+\]/).test(text1[1]);
    var text2_is_A_format = (/\[[^\]]+\]/).test(text2[1]);
    
    console.log(text1_is_A_format ); // true
    console.log(text1_value); // "Read this"
    console.log(text2_is_A_format ); // false
    console.log(text2_value); // "Read this"
    

    (i added a () around "[Read this]" and checked if [] exist)

    Edit2

    Split string on an array of the items we need items

    var a = "[Blah1] [Read this2] [Blah3] [Optional blah4]";
    var re = new RegExp('(\\]\\s*\\[|\\s+\\[|\\]\\s+|\\[|\\])','g'); // Create reg exp (will be used 2 times)
    var b = a.split(re); // Split array on every match
    for(var i = b.length-1; i >= 0; i--){ // remove useless array items
    // We are making a count down for because we remove items from the array
        if(b[i].length == 0 || b[i].match(re))
            b.splice(i, 1);
    }
    console.log(b); // Print : Array [ "Blah1", "Read this2", "Blah3", "Optional blah4" ]