I have a string containing two backslashes in it:
str = "active - error - oakp-ms-001 Volume Usage-E:\ PercentUsed E:\"
I want to pick up only "oakp-ms-001
" from the above string, but as the string contains backslash in it I am not able to split the string.
Please let me know if there is any solution for this?
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.
The backslash ( \ ) is an escape character in Javascript (along with a lot of other C-like languages). This means that when Javascript encounters a backslash, it tries to escape the following character. For instance, \n is a newline character (rather than a backslash followed by the letter n).
It's as simple as: s. split(""); The delimiter is an empty string, hence it will break up between each single character.
delimiter. Optional. It is delimiter used to break the string into the array of substrings. It can be a single character, string or regular expression. If this parameter is not provided, the split() method will return an array with one element containing the string.
First, I'll note that the code you've quoted has a syntax error:
str = "active - error - oakp-ms-001 Volume Usage-E:\ PercentUsed E:\"
There's no ending "
on that string, becaue the \"
at the end is an escaped "
, not a backslash followed by an ending quote.
If there were an ending quote on the string, it would have no backslashes in it (the \
with the space after it is an invalid escape that ends up just being a space).
So let's assume something valid rather than a syntax error:
str = "active - error - oakp-ms-001 Volume Usage-E:\\ PercentUsed E:\\";
That has backslashes in it.
What you need to do doesn't really involve "splitting" at all but if you want to split on something containing a backslash:
var parts = str.split("\\"); // Splits on a single backslash
But I'm not seeing how splitting helps with what you've said you want.
You have to identify what parts of the string near what you want are consistent, and then create something (probably a regular expression with a capture group) that can find the text that varies relative to the text that doesn't.
For instance:
var str = "active - error - oakp-ms-001 Volume Usage-E:\\ PercentUsed E:\\";
var match = str.match(/error - (.*?) ?Volume/);
if (match) {
console.log(match[1]); // oakp-ms-001
}
There I've assumed the "error - "
part and the "Volume"
part (possibly with a space in front of it) are consistent, and that you want the text between them.
Live Example
JSON.stringify(fileName).split(“\”);
It’s should be double backslash inside the split
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With