Javascript字符串操作-小写,替换,修剪,分割

Javascript String Manipulation - lowercase, replace, trim, split

本文关键字:替换 分割 修剪 小写 字符串 操作 Javascript      更新时间:2023-09-26

我可以使用preg_replace在PHP中管理这一点,但我需要在JavaScript中做到这一点,我很挣扎!

我将从数据库中获得起始字符串,例如:-

Black Pudding with Eggs

Sausage and Crispy Bacon

等等等等-总是两个"事物"被"and"或"with"分开。"事物"可以是1个、2个或更多的单词。

我需要从这些是3个新的变量-两者在一起,每个"东西"单独("main"附加到第一个东西和"side"附加到第二个)。所有字符都应该是小写,任何空格都改为下划线,没有前导或训练空格。所以上面的代码会给我:-

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

和从第二个:-

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

它所在的网站已经在使用jQuery了,所以这是一个选项,如果这样更容易的话…

任何帮助都非常感谢!

不需要jQuery。您可以将字符串拆分为一个数组,并使用.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
    };
}

然后,你可以得到这样的部分:

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

示例:https://jsfiddle.net/TheQueue841/tujdb98y/

注意,这个方法需要输入"and"或"with",否则就会出错。可以很容易地修改,以适应必要的

嗯,不需要正则表达式或任何特殊的东西。如果您有这样清晰的字符串,您可以这样做(示例中的第三个字符串可能有点问题:))

我稍微注释了一下代码,但是如果你需要更多的信息,请随时询问

'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)); 

该方法接受输入中没有'and'或'with'的字符串。它还可以正确地处理单词中包含and或with的短语。例如,s 湿草地, 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`  
    };  
}

请像这样使用:

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     ''