简体   繁体   中英

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!

Well, no need for regex or anything special. If you have such clear strings, you can do it like this ( the third string in the example can be a bit more problematic :) )

I commented the code a bit, but if you need more info feel free to ask

 'use strict'; var input1 = 'Black Pudding with Eggs', input2 = 'Sausage and Crispy Bacon', input3 = 'Steak with colliflower and fries'; function getSplittedText(input) { if (!input || !input.toLowerCase) { // no text or not a string return null; } // make it lowercase, and replace all spaces with underscore var parsed = input.toLowerCase().replace(/ /g, '_'), splitWith = '_with_', results = [parsed]; // add the parsed text to the array // in case the sentence has _and_ in it, use _and_ to split the text if (parsed.indexOf('_and_') >= 0) { splitWith = '_and_'; } // split the text with either _and_ or _with_ and add the results to the array parsed.split( splitWith ).forEach(function(item, i) { results.push(item + (i == 0 ? '_main' : '_side')); // if it's 0, it will be main, if not it will be a side }); return results; } console.log(getSplittedText(input1)); console.log(getSplittedText(input2)); // this one is a bit tricky, probably you might have to think about better ones... console.log(getSplittedText(input3));

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.

This method accepts strings without 'and' or 'with' in input. It also properly treats phrases that contain 'and' or 'with' in the words. For eg, s and wich , with al

function parseString(string) 
{
    string      = string.trim().replace(/ /g,'_').toLowerCase();//replace spaces with _ and convert to lowercase 
    var parts   = string.split('_with_')[0] === string? string.split('_and_') : string.split('_with_');  
    if(parts[0] === string)//if there's NO 'with' or 'and' in the string
    {    
        return {
            together: string,
            main:  ``, 
            side:  ``  
        };
    }   
    return {//if there's a 'with' or 'and' in the string
        together: string,
        main:  `${parts[0]}_main`, 
        side:  `${parts[1]}_side`  
    };  
}

Please use like so:

Example 1: 
var result = parseString('Sausage and Crispy Bacon'); 
//result.together outputs 'sausage_and_crispy_bacon'
//result.main outputs      'sausage_main'
//result.side outputs      'crispy_bacon_side'

Example 2: 
var result = parseString('Black Pudding with Eggs'); 
//result.together outputs 'black_pudding_with_eggs'
//result.main outputs     'black_pudding_main'
//result.side outputs     'eggs_side'

Example 2: 
var result = parseString(''Sunshine Sandwiches Withal''); 
//result.together outputs 'sunshine_sandwiches_withal'
//result.main outputs     ''
//result.side outputs     ''

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM