【问题标题】:JavaScript how to split conjoining string on UpperCase and LowerCase CharactersJavaScript如何在大写和小写字符上拆分连接字符串
【发布时间】:2021-04-14 04:33:00
【问题描述】:

如何拆分这个字符串,它有小写和大写字符。

这是我的字符串:

string = "Absolute Organic Diced TomatoesCobs Natural Popcorn - Best Ever ButterCobs Natural Popcorn - Cheese"

这是尝试过的,我从 PDF 中提取了这个字符串,这是来自表格的信息:

let description = [];
for (let line = 0; line < lineItem_array2.length; line++) {
description += lineItem_array2[line].split(" ").slice(4, -5).join(" "); } 

这是我想要的结果:

result = "Absolute Organic Diced Tomatoes", "Cobs Natural Popcorn - Best Ever Butter", "Cobs Natural Popcorn - Cheese"

【问题讨论】:

  • 最好的解决方案是在他们加入的源头修复它。除此之外,您还尝试过什么?
  • 这是尝试过的,我从 PDF 中提取了这个字符串,这是来自表格的信息。让描述 = []; for (let line = 0; line
  • 情节变厚了。这就是产生这个字符串的原因吗?如果是这样,需要在问题本身中更多地扩展细节。如果不是产生字符串的原因...lineItem_array2 是什么?
  • 什么是正确的? Edit 包含所有细节和数据样本的问题。你最初问的是XY problem

标签: javascript arrays string


【解决方案1】:

你可以使用这个功能来解决这种情况,这个功能可以满足你的需要。只需将您的字符串作为输入

我添加了另一个字符串来显示它是如何工作的

正则表达式用于查找索引,子字符串方法用于拆分字符串,字符串的其余部分用于再次迭代希望这可以帮助某人

function format(str){
    let index = 0;
    let i =0;
    let result = [];
    while(index != -1){
        index = str.search(/[a-z][A-Z][a-z]/);
        const splited = index !== -1 ? str.substring(0, index+1) : str;
        result.push(splited)
        str = str.substring(index+1, str.length);
    }
    return result
}

string = "Absolute Organic Diced TomatoesCobs Natural Popcorn - Best Ever ButterCobs Natural Popcorn - Cheese"

string1 = "Absolute Organic Diced TomatoesCobs Natural Popcorn - Best Ever ButterCobs Natural Popcorn - CheeseAbsolute Organic Diced TomatoesCobs Natural Popcorn - Best Ever ButterCobs Natural Popcorn - CheeseAbsolute Organic Diced TomatoesCobs Natural Popcorn - Best Ever ButterCobs Natural Popcorn - Cheese"

console.log("string:", format(string))
console.log("String1: ",format(string1))

【讨论】:

    【解决方案2】:

    它很草率,但你会得到漂移

    var splitedBySpace = "Absolute Organic Diced TomatoesCobs Natural Popcorn - Best Ever ButterCobs Natural Popcorn - Cheese".split(" ");
        var result = "";
        splitedBySpace.forEach(function(word){
            var splitByUpperCase = word.match(/[A-Z][a-z]+/g);
            debugger
            if(splitByUpperCase && splitByUpperCase.length>1){
                for(var i =0 ; i<= splitByUpperCase.length-1 ;i++){
                    if(i== splitByUpperCase.length-1){
                        result = result.concat(splitByUpperCase[i]+" ");
                    }else{
                        result = result.concat(splitByUpperCase[i]+",");
                    }
                    
                }
                
            }else{
                result = result.concat(word+" ")
            }
        })
        console.log(result.split(","));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-04
      • 2020-06-05
      • 2022-06-28
      • 2021-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-22
      相关资源
      最近更新 更多