如何使用Javascript将数组字符串拆分为两组

时间:2017-09-24 23:56:21

标签: javascript arrays string

我给出了一系列字符串。它是一个带括号内动作的文本。实施例

"John sees his neighbor and greets 'Hello!' [waves]. But she didn't hear him."

我喜欢的最终结果是

actionArray = "                                           [waves]

speechArray = "John sees his neighbor and greets 'Hello!'.       But she didn't hear him."

actionArray将为每个字符间隔,以便在操作期间action标记位于speechArray之上。我使用以下方法解决了这个问题。

var array = data.toString().split("\n");
  for(i in array) {
    var actionArray = "";
    var speechArray = "";
    for (var letter in array[i]){
      if (array[i][letter] == "["){
        actionArray += array[i][letter];
        letter++;
        while(array[i][letter] !== "]"){
          actionArray += array[i][letter];
          letter++;
        }
        if (array[i][letter] == "]"){
          actionArray += array[i][letter];
        }

      }

      if (array[i][letter] !== "["){

        speechArray += array[i][letter];
        actionArray += " ";
      }

因此,为了使用动作括号提取字符串的一部分,我有一个if方法找到" ["如果确实如此,它会将它添加到actionArray中,与if一起保存并添加到actionArray,直到找到结束标记"]"

它有效,但是在找到结束标记后,计数器letter不会继续我停止的位置,因此整个字符串最终仍会被复制到speechArray。然后我最终得到这样的东西

actionArray = "                                           [waves]

speechArray = "John sees his neighbor and greets 'Hello!'.[waves] But she didn't hear him."

我是Javascript的新手,没有使用指针,我不知道如何处理这个问题。有人能指出我正确的方向吗?谢谢!

5 个答案:

答案 0 :(得分:1)

只需要一个变量来告诉你你是否"内部"行动并相应地分配:



str = "John sees his neighbor and greets 'Hello!' [waves]. But she didn't hear him.";


let action = '',
    speech = '',
    inAction = false;

for (let char of str) {
    if (char === '[')
        inAction = true;
    if (inAction) {
        action += char;
        speech += ' ';
    } else {
        action += ' ';
        speech += char;
    }
    if (char === ']')
        inAction = false;
}


console.log(action)
console.log(speech)




对于正则表达式来说,这是一个更简洁但更不易读的解决方案:



str = "John sees his neighbor and greets 'Hello!' [waves]. But she didn't hear him.";

let parts = ['', ''];

str.replace(/(\[.+?\])|[^\]\[]+/g, function (m, a) {
    parts[a ? 1 : 0] += m;
    parts[a ? 0 : 1] += ' '.repeat(m.length);
});

console.log(parts[1]);
console.log(parts[0]);




答案 1 :(得分:0)

您可以查看以下简单的代码段:

list contains exact match: true
list contains match on first element: true
TreeSet contains exact match: true
TreeSet contains match on first element: false

输出应为:

var data = "John sees his neighbor and greets 'Hello!' [waves]. But she didn't hear him."
var arr = data.split("");
var action = false;
var actionstr="",speachstr="";
    for(var i=0;i<arr.length;i++){
        if(arr[i]=='['){
            action = true
        }else if(arr[i] ==']'){

            actionstr = actionstr.concat(arr[i])
            speachstr = speachstr.concat(" ")
            action = false
            continue
        }
        if(action){
            actionstr = actionstr.concat(arr[i])
            speachstr = speachstr.concat(" ")
        }else{
            actionstr = actionstr.concat(" ")
            speachstr = speachstr.concat(arr[i])
        }
    }
    console.log(actionstr)
    console.log(speachstr)

答案 2 :(得分:0)

我有以下实施,也许你可能没问题

1) Tap on a text field to begin editing and bring up the keyboard
2) Enter in some text
3) Tap the clear button (which is enabled on the text field)
4) Tap on another textfield in the same table view

答案 3 :(得分:0)

使用正则表达式的简单解决方案。

首先是简单部分(speechString):

var speechString = string.replace(/(\[[^\]]*\])/gi, (v)=>' '.repeat(v.length));

它只是将[...]替换为空格数等于匹配的长度。

现在更难的部分(actionString):

var actionString = ((string)=>{
    var ret = '';
  var re = /(\[[^\]]*\])/gi;
    var l = 0;
    while((m = re.exec(string)) != null) {
        ret += ' '.repeat(m.index-l) + string.substring(m.index, m.index+m[1].length);
        l = m.index+m[1].length;
    }
    return ret;
})(string);

它定义了相同的regularrexpression来查找[...],但使用索引(匹配的位置)和匹配的长度来构建一个像预期的字符串。

Here是一个工作小提琴。

编辑 actionString也可以通过一个语句检索:

var actionString = string.replace(/([^\[]*)(\[[^\]]+?\])?/g, (v,p1,p2)=>{
  return (p1?' '.repeat(p1.length):'')+(p2||'');
});

匹配所有字符和[...]表达式,并将其替换为附加p2匹配的第一个组长度的空格。

答案 4 :(得分:-1)

您可以将String.prototype.match()String.prototype.replace()RegExp /\[.+\]/匹配,以匹配"["中开头的字符,后跟一个或多个字符,后跟并包括{ {1}},"]"

String.prototype.repeat()
let str = "John sees his neighbor and greets 'Hello!' [waves]. But she didn't hear him.";

let re = /\[.+\]/;

let match = str.match(re);

let res = " ".repeat(match.index) + match[0] 
          + " ".repeat(str.length - (match.index + match[0].length));

str = str.replace(re, " ".repeat(match[0].length));

let pre = document.querySelector("pre");

pre.textContent = res + "\n" + str;