Javascript String Manipulation - 小写,替换,修剪,拆分

时间:2016-10-12 17:43:38

标签: javascript jquery regex string replace

我可以使用preg_replace在PHP中管理这个,但我需要在JavaScript中完成它,而且我很难挣扎!

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

Black Pudding with Eggs

Sausage and Crispy Bacon

等等 - 总是2个“事物”被“和”或“带”分开。 “事物”可以是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,所以这是一个选项,如果这样可以更容易......

任何帮助都非常感谢!

3 个答案:

答案 0 :(得分:1)

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

我对代码进行了一些评论,但如果您需要更多信息,请随时询问

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

答案 1 :(得分:1)

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

black_pudding_with_eggs getOrder('Black Pudding with Eggs').main

black_pudding_main getOrder('Black Pudding with Eggs').side

eggs_side

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

请注意,此方法需要"和"或"用"在输入中,否则事情就会破裂。可以轻松修改以适应那些必要的。

答案 2 :(得分:0)

此方法接受输入中不包含“ and”或“ with”的字符串。 它还可以正确处理单词中包含“ and”或“ with”的短语。例如s wich,带有 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     ''