How to split a string with a backslash in javascript? - javascript

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?

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

This is a non-terminating string to begin with (you're escaping the closing quotation mark), so I'm going to assume your string looks more like this:
str = "active - error - oakp-ms-001 Volume Usage-E:\\ PercentUsed E:\\";
If you want to split the string by backslashes and spaces alike, the first step is to split by backslashes, done like this:
step2 = str.split("\\");
Note that you have to escape the backslash here.
The second thing to do is to now split this string by spaces, but because it's an array you have to use a loop to do this:
var step3 = [];
for(var i = 0; i < step2.length; i++){
step3 += step2[i].split(" ");
}
And then you can simply split step3 by "," characters and find the phrase before "Volume". This probably isn't the best answer, but it gets you the data you want.

escape your backslash! \ becomes \\ so in fact you assign like ths:
str = "active - error - oakp-ms-001 Volume Usage-E:\\ PercentUsed E:\\"

This is a solution for this question
str.split(/[\$]/)

Related

RegEx issue in JavaScript Function - Not replacing anything

Plan A: it's such a simple function... it's ridiculous, really. I'm either totally misunderstanding how RegEx works with string replacement, or I'm making another stupid mistake that I just can't pinpoint.
function returnFloat(str){
console.log(str.replace(/$,)( /g,""));
}
but when I call it:
returnFloat("($ 51,453,042.21)")
>>> ($ 51,453,042.21)
It's my understanding that my regular expression should remove all occurrences of the dollar sign, the comma, and the parentheses. I've read through at least 10 different posts of similar issues (most people had the regex as a string or an invalid regex, but I don't think that applies here) without any changes resolving my issues.
My plan B is ugly:
str = str.replace("$", "");
str = str.replace(",", "");
str = str.replace(",", "");
str = str.replace(" ", "");
str = str.replace("(", "");
str = str.replace(")", "");
console.log(str);
There are certain things in RegEx that are considered special regex characters, which include the characters $, ( and ). You need to escape them (and put them in a character set or bitwise or grouping) if you want to search for them exactly. Otherwise Your Regex makes no sense to an interpreter
function toFloat(str){
return str.replace(/[\$,\(\)]/g,'');
}
console.log(toFloat('($1,234,567.90'));
Please note that this does not conver this string to a float, if you tried to do toFloat('($1,234,567.90)')+10 you would get '1234568.9010'. You would need to call the parseFloat() function.
the $ character means end of line, try:
console.log(str.replace(/[\$,)( ]/g,""));
You can fix your replacement as .replace(/[$,)( ]/g, "").
However, if you want to remove all letters that are not digit or dot,
and easier way exists:
.replace(/[^\d.]/g, "")
Here \d means digit (0 .. 9),
and [^\d.] means "not any of the symbols within the [...]",
in this case not a digit and not a dot.
if i understand correctly you want to have this list : 51,453,042.21
What you need are character classes. In that, you've only to worry about the ], \ and - characters (and ^ if you're placing it straight after the beginning of the character class "[" ).
Syntax: [characters] where characters is a list with characters to be drop( in your case $() ).
The g means Global, and causes the replace call to replace all matches, not just the first one.
var myString = '($ 51,453,042.21)';
console.log(myString.replace(/[$()]/g, "")); //51,453,042.21
if you want to delete ','
var myString = '($ 51,453,042.21)';
console.log(myString.replace(/[$(),]/g, "")); //51453042.21

Escape single backslash inbetween non-backslash characters only

I have some input coming in a web page which I will re display and submit elsewhere. The current issue is that I want to double up all single backslashes that are sandwiched inbetween non-backslash characters before submitting the input elsewhere.
Test string "domain\name\\nonSingle\\\WontBe\\\\Returned", I want to only get the first single backslash, between domain and name.
This string should get nothing "\\get\\\nothing\\\\"
My current pattern that I can get closest with is [\w][\\](?!\\) however this will get the "\n" from the 1st test string i have listed. I would like to use lookbehind for the regex however javascript does not have such a thing for the version I am using. Here is the site I have been testing my regexs on http://www.regexpal.com/
Currently I am inefficiently using this regex [\w][\\](?!\\) to extract out all single backslashes sandwiched between non-backslash characters and the character before them (which I don't want) and then replacing it with the same string plus a backslash at the end of it.
For example given domain\name\\bl\\\ah my current regex [\w][\\]\(?!\\) will return "n\". This results in my code having to do some additional processing rather than just using replace.
I don't care about any double, triple or quadruple backslashes present, they can be left alone.
For example given domain\name\\bl\\\ah my current regex [\w][\\]\(?!\\) will return "n\". This results in my code having to do some additional processing rather than just using replace.
It will do just using replace, since you can insert the matched substring with $&, see:
console.log(String.raw`domain\name\\bl\\\ah`.replace(/\w\\(?!\\)/g, "$&\\"))
Easiest method of matching escapes, is to match all escaped characters.
\\(.)
And then in the replacement, decide what to do with it based on what was captured.
var s = "domain\\name\\\\backslashesInDoubleBackslashesWontBeReturned";
console.log('input:', s);
var r = s.replace(/\\(.)/g, function (match, capture1) {
return capture1 === '\\' ? match : '$' + capture1;
});
console.log('result:', r);
The closest you can get to actually matching the unescaped backslashes is
((?:^|[^\\])(?:\\\\)*)\\(?!\\)
It will match an odd number of backslashes, and capture all but the last one into capture group 1.
var re = /((?:^|[^\\])(?:\\\\)*)\\(?!\\)/g;
var s = "domain\\name\\\\escapedBackslashes\\\\\\test";
var parts = s.split(re);
console.dir(parts);
var cleaned = [];
for (var i = 1; i < parts.length; i += 2)
{
cleaned.push(parts[i-1] + parts[i]);
}
cleaned.push(parts[parts.length - 1]);
console.dir(cleaned);
The even-numbered (counting from zero) items will be unmatched text. The odd-numbered items will be the captured text.
Each captured text should be considered part of the preceding text.

How to replace all \n with space? [duplicate]

I have a var that contains a big list of words (millions) in this format:
var words = "
car
house
home
computer
go
went
";
I want to make a function that will replace the newline between each word with space.
So the results would something look like this:
car house home computer go went
You can use the .replace() function:
words = words.replace(/\n/g, " ");
Note that you need the g flag on the regular expression to get replace to replace all the newlines with a space rather than just the first one.
Also, note that you have to assign the result of the .replace() to a variable because it returns a new string. It does not modify the existing string. Strings in Javascript are immutable (they aren't directly modified) so any modification operation on a string like .slice(), .concat(), .replace(), etc... returns a new string.
let words = "a\nb\nc\nd\ne";
console.log("Before:");
console.log(words);
words = words.replace(/\n/g, " ");
console.log("After:");
console.log(words);
In case there are multiple line breaks (newline symbols) and if there can be both \r or \n, and you need to replace all subsequent linebreaks with one space, use
var new_words = words.replace(/[\r\n]+/g," ");
See regex demo
To match all Unicode line break characters and replace/remove them, add \x0B\x0C\u0085\u2028\u2029 to the above regex:
/[\r\n\x0B\x0C\u0085\u2028\u2029]+/g
The /[\r\n\x0B\x0C\u0085\u2028\u2029]+/g means:
[ - start of a positive character class matching any single char defined inside it:
\r - (\x0D) - \n] - a carriage return (CR)
\n - (\x0A) - a line feed character (LF)
\x0B - a line tabulation (LT)
\x0C - form feed (FF)
\u0085 - next line (NEL)
\u2028 - line separator (LS)
\u2029 - paragraph separator (PS)
] - end of the character class
+ - a quantifier that makes the regex engine match the previous atom (the character class here) one or more times (consecutive linebreaks are matched)
/g - find and replace all occurrences in the provided string.
var words = "car\r\n\r\nhouse\nhome\rcomputer\ngo\n\nwent";
document.body.innerHTML = "<pre>OLD:\n" + words + "</pre>";
var new_words = words.replace(/[\r\n\x0B\x0C\u0085\u2028\u2029]+/g," ");
document.body.innerHTML += "<pre>NEW:\n" + new_words + "</pre>";
Code : (FIXED)
var new_words = words.replace(/\n/g," ");
Some simple solution would look like
words.replace(/(\n)/g," ");
No need for global regex, use replaceAll instead of replace
myString.replaceAll('\n', ' ')

Javascript: regex escaped space

I have a directory with space on unix, so the space is backslashed. And I need to replace the backslashed space with semicolon. Tried multiple regex'es but not able to find the answer
var str = '/test\ space/a.sh -pqr';
So I am looking to get this after the replace /test;space/a.sh -pqr
console.log("replace: ", str.replace(/\\\s+/g, ";")); //This one doesn't work, (formatting is taking out one backslash)
Your regular expression is correct.
It's your example string that is incorrect - the \ is not properly escaped:
var str = '/test\\ space/a.sh -pqr';
See the fiddle and read more special characters in JavaScript strings.

javascript replace all occurrences ",\S" with ", \S"

I want to have spaces separating items in a CSV string. That is "123,456,789" => "123, 456, 789". I have tried, but been unable to construct a regexp to do this. I read some postings and thought this would to the trick, but no dice.
text = text.replace(new RegExp(",\S", "g"), ", ");
Could anyone show me what I am doing wrong?
You have two problems:
Backslashes are a pain in the, um, backslash; because they have so many meanings (e.g. to let you put a quote-mark inside a string), you often end up needing to escape the backslash with another backslash, so you need ",\\S" instead of just ",\S".
The \S matches a character other than whitespace, so that character gets removed and replaced along with the comma. The easiest way to deal with that is to "capture" it (by putting it in parentheses), and put it back in again in the replacement (with $1).
So what you end up with is this:
text = text.replace(new RegExp(',(\\S)', "g"), ", $1");
However, there is a slightly neater way of writing this, because JavaScript lets you write a regex without having a string, by putting it between slashes. Conveniently, this doesn't need the backslash to be escaped, so this much shorter version works just as well:
text = text.replace(/,(\S)/g, ", $1");
As an alternative to capturing, you can use a "zero-width lookahead", which in this situation basically means "this bit has to be in the string, but don't count it as part of the match I'm replacing". To do that, you use (?=something); in this case, it's the \S that you want to "look ahead to", so it would be (?=\S), giving us this version:
text = text.replace(/,(?=\S)/g, ", ");
There are 2 mistakes in your code:
\S in a string literal translates to just S, because \S is not a valid escape sequence. As such, your regex becomes /,S/g, which doesn't match anything in your example. You can escape the backslash (",\\S") or use a regex literal (/,\S/g).
After this correction, you will replace the character following the comma with a space. For instance, 123,456,789 becomes 123, 56, 89. There are two ways to fix this:
Capture the non-space character and use it in the replacement expression:
text = text.replace(/,(\S)/g, ', $1')
Use a negative lookahead assertion (note: this also matches a comma at the end of the string):
text = text.replace(/,(?!\s)/g, ', ')
text = text.replace(/,(\S)/g, ', $1');
try this:
var x = "123,456,789";
x = x.replace(new RegExp (",", "gi"), ", ");

Categories

Resources