简体   繁体   English

将数组转换为字符串Javascript

[英]Convert array to string Javascript

didn't find the solution in SPLIT function.. i was trying to convert a string into array.. String is like. 没在SPLIT函数中找到解决方案。。我试图将字符串转换为数组。

My name-- is ery and your-- is this

i just want to convert that string to array, and then print it out but while getting this '-- ' break the line too. 我只想将该字符串转换为数组,然后将其打印出来,但是在获得此'-'时也要换行。

i have did that so far 到目前为止,我已经做到了

function listToAray(fullString, separator) {
  var fullArray = [];

  if (fullString !== undefined) {
    if (fullString.indexOf(separator) == -1) {
      fullAray.push(fullString);
    } else {
      fullArray = fullString.split(separator);
    }
  }

  return fullArray;
}

but is for Comma separated words in string, but what i want is to just convert string to array and then print it out while breaking line on getiing '-- ' this is array Thanks in advance 但是是用逗号分隔的字符串中的单词,但是我想要的只是将字符串转换为数组,然后在getiing'-'上换行时打印出来,这是数组

seems to work : 似乎工作:

text = "My name-- is ery and your-- is this";


function listToAray(fullString, separator) {
  var fullArray = [];

  if (fullString !== undefined) {
    if (fullString.indexOf(separator) == -1) {
      fullAray.push(fullString);
    } else {
      fullArray = fullString.split(separator);
    }
  }

  return fullArray;
}


console.log(listToAray(text,"--"));

console output: 控制台输出:

["My name", " is ery and your", " is this"] 

what do you expect ? 你能指望什么 ?

You can use the split method: 您可以使用split方法:

var str = "My name-- is ery and your-- is this";
var res = str.split("--");
console.log(res);

// console output will be:

["My name", " is ery and your", " is this"] 

Why are you doing all that complicated stuff man? 你为什么要做所有这些复杂的事情? There is a .split() method that allows you to do that in a single line of code: 有一个.split()方法可让您在一行代码中完成此操作:

text = "My name-- is ery and your-- is this";
array = text.split('--');

> ["My name", " is ery and your", " is this"]

Now if you want to break line on -- then you can do the following: 现在,如果你想打破在线--那么你可以做到以下几点:

text = "My name-- is ery and your-- is this";
list = text.replace(/\-\-/g, '\n');
console.log(list);

> "My name
  is ery and your
  is this"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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