1

var numbers = "3+3/2";

console.log(numbers);

var numArr = numbers.split(" ");
console.log(numArr);
numArr.splice(1, 3, '1');
console.log(numArr);
numbers = numArr.toString();

console.log(numbers);
var numbers = "3+3/2";

console.log(numbers);

var numArr = numbers.split(" ");
console.log(numArr);
numArr.splice(1, 3, '1');
console.log(numArr);
numbers = numArr.toString();

console.log(numbers);

I am trying to convert the whole string into an array. Then use the splice to edit the numArr Then change the original string, numbers

  • 2
    Does this answer your question? [How do I split a string into an array of characters?](https://stackoverflow.com/questions/6484670/how-do-i-split-a-string-into-an-array-of-characters). See the second answer especially. – marsnebulasoup Dec 27 '20 at 21:39
  • 2
    You can just use spread. `let strs = [..."3+3/2"]` – ptothep Dec 27 '20 at 21:40
  • `"3+3/2".split("")` without the space between quotes. – kosmos Dec 27 '20 at 21:40
  • @kosmos - apparently, that's not recommended: https://stackoverflow.com/a/38901550/8402369 ...but it may be fine if no special chars are used. – marsnebulasoup Dec 27 '20 at 21:41

2 Answers2

2

I'd use a regular expression to either match numbers or non-space, non-digit characters:

var numbers = "3+3/2";
console.log(
  numbers.match(/\d+|[^\s\d]+/g)
);
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

You could split the string with nonnumber characters.

var numbers = "3+3/2",
    parts = numbers.split(/(\D+)/);

console.log(parts);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392