Home > Enterprise >  How to split string with character \ - Javascript
How to split string with character \ - Javascript

Time:04-09

I want to split a string into an array of letters, but I have a problem with the special character \ .

The code:

let s = '\op*Bw'.split('');

But I got this result ['o', 'p', '*', 'B', 'w'], that is not correct because I want the \ character too in the array.

CodePudding user response:

Backslashes '\' escape the next character in the sequence. If you need the '\' in the string, your string will need to look like '\\op*Bw'

let s = '\\op*Bw'.split('');
console.log(s) // ['\', 'o', 'p', '*', 'B', 'w']

CodePudding user response:

You can also use String.raw

String.raw`\op*Bw`.split('')
  • Related