Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split Javascript string containing single backslash to two strings

Tags:

javascript

Consider this below string in JavaScript:

"TEST NAME\TEST ADDRESS" 

(it contains only one "\" which cannot be changed).

Now, this above string needs to be split into two string by "\" char.

Resulting strings:

"TEST NAME"
"TEST ADDRESS"

How, can this be done in JavaScript?

like image 745
Smart B0y Avatar asked Nov 05 '13 08:11

Smart B0y


People also ask

How do you split a string with a backslash?

split() method to split a string on the backslashes, e.g. my_list = my_str. split('\\') . The str. split method will split the string on each occurrence of a backslash and will return a list containing the results.

How can I split a string into two JavaScript?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

How do you remove a single backslash from a string?

Use the String. replaceAll() method to remove all backslashes from a string, e.g. str. replaceAll('\\', '') . The replaceAll() method will remove all backslashes from the string by replacing them with empty strings.


2 Answers

Do like this:

var str = "TEST NAME/TEST ADDRESS";
var res = str.split("/");

You will get first part on res[0] and second part on res[1].

like image 69
Md. Al-Amin Avatar answered Sep 24 '22 11:09

Md. Al-Amin


var str = "TEST NAME\\TEST ADDRESS"; // Show: TEST NAME\TEST ADDRESS
console.log(str);
var res = str.split("\\");
console.log(res);
like image 27
Sky Voyager Avatar answered Sep 25 '22 11:09

Sky Voyager