John A John A - 1 month ago 15
Javascript Question

Javascript String Manipulation - lowercase, replace, trim, split

I could probably manage this in PHP using preg_replace, but I need to do it in JavaScript, and I'm struggling!

I'll be getting starting strings from a database, for example: -

Black Pudding with Eggs


or

Sausage and Crispy Bacon


etc etc. - always 2 "things" split by either an "and" or a "with". The "things" can be 1, 2 or more words.

What I need from these is 3 new variables - both together, and each "thing" individually (with "main" appended to the first thing and "side" appended to the second). All should be lowercase, with any spaces changed to underscores, and no leading or training spaces. So the above would give me: -

var1 : 'black_pudding_with_eggs'
var2 : 'black_pudding_main'
var3 : 'eggs_side'


and from the 2nd one: -

var1 : 'sausage_and_crispy_bacon'
var2 : 'sausage_main'
var3 : 'crispy_bacon_side'


The site it's on already uses jQuery so that's an option, if that makes it easier...

Any help greatly appreciated!

Answer

jQuery isn't necessary. You can split the string into an array and convert it using .replace().

function getOrder(input) {
    var item = input.replace(/ /g, '_').toLowerCase();

    // there's probably a better way of splitting this, but I can't think of it.
    var dish = (input.indexOf(' and ') > -1) ? input.split(' and ') : input.split(' with ');

    var main = dish[0].replace(/ /g, '_').toLowerCase() + "_main";
    var side = dish[1].replace(/ /g, '_').toLowerCase() + "_side";

    // returns a JS object so to have access to all properties in one function
    return {
        item: item,
        main: main,
        side: side
    };
}

Then, you can get the parts like this:

getOrder('Black Pudding with Eggs').item for black_pudding_with_eggs

getOrder('Black Pudding with Eggs').main for black_pudding_main

getOrder('Black Pudding with Eggs').side for eggs_side

Example here: https://jsfiddle.net/TheQueue841/tujdb98y/

Note that this method expects " and " or " with " in the input, otherwise things break. Can be easily modified to accommodate for those if necessary.