How to differentiate " and \" in Javascript - javascript

Let's say I have a string like this '"\"'. The length of this string is 2. So I wonder if there's any way I can differentiate the first " and the second \"? Thanks.
I'm trying to parse a string and I want to turn on/off a flag when " is encountered, but ignore the \".

It's not possible. The two characters are equal to each other, because the backslash gets interpreted as an unnecessary escape character, and gets discarded:
const str = '"\"';
console.log(str[0] === str[1], str.length);
If you wanted to put a literal backslash into the string, either put two backslashes in there:
const str = '"\\"';
console.log(str.length);
Or use String.raw, in which (nearly) every character gets interpreted literally, without escaping:
const str = String.raw`"\"`;
console.log(str.length);

Related

JSON stringify and use of \

assert(JSON.stringify(searchForMatches(searchData,['cats']))==='["catcode.io","catgifs.co"]',"The result should be '[\"catcode.io\",\"catgifs.co\"]'");
Why do I need the use of \ at the end multiple times? It throws an error otherwise. Is it specific to JSON.stringify and/or when/how should I go about about using it in future instances?
\ is an escape operator. It prevents the language from parsing the next char as syntax relevant, so without it your string stops at the next " after the first " which starts the string.
The backslash is a JavaScript operator used within a string for escaping a special character.
In your case it is escaping a quotation. See this example:
// in this case it escapes the " symbol because that would end the string.
var x = "\"";
This is the same as:
// in this case you don't need to escape it because
// the string begins with the apostrophe instead of the " character
var x = '"';
In both cases console.log(x); will print a single quote character.

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

adding escape character to a string in javascript

<html>
<body>
<p id="demo"></p>
<script>
var x = 'It\'s \#lright';
var y = "We are the so-called \"Vikings\" from the north.";
var i;
var s = "";
var z = "Thi$ is * a# demo";
var patt = "[^A-Za-z0-9\\s]";
for(i=0;i<z.length;i++){
if(z[i].match(patt)){
s+= "\\"+z[i];
}
else{
s+= z[i];
}
}
document.getElementById("demo").innerHTML = x + "<br>" + y + "<br>" + s;
</script>
</body>
</html>
The output for the above script I get is :
It's #lright
We are the so-called "Vikings" from the north.
Thi\$ is \* a\# demo
I don't know why for the strings x and y, if I add any special character followed by '\' (backslash), strings are displayed as it is with the special characters. But when I do it to string s by appending '\' before each special character, the string gets displayed with '\' preceding the special characters.
Can someone explain me this? And also please tell me how to add '\' before each special character in such a way that when I print the string I only see the special characters (not with '\' prepended in front of them as happening now)?
why for the strings x and y, if I add any special character followed by '\'(backslash), strings are displayed as it is with the special characters
Because the escape character is part of string literal syntax, and you create x and y with string literals.
When the JavaScript source code is parsed into a string primitive, the escape sequences are converted to the characters they represent.
But when I do it to string s by appending '\' before each special character
Because then you aren't using string literals. "\\" is a string literal and the escape character followed by the backslash becomes a backslash in the data of the string primitive.
When you concatenate that with another string primitive, you are no longer at the parsing source code stage, you have a backslash in the data.
And also please tell me how to add '\' before each special character in such a way that when I print the string I only see the special characters(not with '\' appended in front of them as happening now)?
Do nothing. The data already has the special characters in it.
It doesn't make sense to take something which already exists in the form you want, and then modify it to get the form you want.
The backslash character is the indicator of a string escape character. When it is found in a string, the JavaScript runtime knows that the character that will follow it dictates what actual character to escape. If you just want to include a single backslash, then you'll have to provide the escape code for that, which is two backslashes.
console.log("\"This string has double quotes embedded within double quotes\"");
// If we want to output a single backslash, we need to escape with with \\
// So, if we want to produce two of them, we need \\\\
console.log("The escape code for a \\ is \\\\");
console.log("The escape code for a \' is \\'");
console.log("The escape code for a \" is \\\"");
Now, it's important to distinguish a "JavaScript" string escape sequence with an HTML entity code.
If you take a JavaScript string that includes JavaScript escape characters and send that string to be parsed by the HTML parser, the escape sequences will have already been processed and the HTML parser will be receiving the result of that work. The HTML parser will just render the actual characters that were passed as it normally would.
The JavaScript escape characters only have meaning when processed by the JavaScript runtime, not the HTML parser:
var x = "This will be split over two lines when processed by the JavaScript runtime, \n\nbut the escape code will will just cause normal carriage return white space for the HTML parser";
var y = "\"To escape or not to escape\"";
// Escape code will be parsed and result in two groups of text
alert(x);
// Here, the result of the escaping will be passed to the HTML parser for further processing
// But here, the new line characters embedded within the string will be treated as all exteraneous
// white space in an HTML document is - - it will be normalized down to a single space.
document.querySelector("#d1").innerHTML = x;
document.querySelector("#d2").innerHTML = y;
<div id="d1"></div>
<div id="d2"></div>

How to split a string with a backslash in 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(/[\$]/)

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