We can work with escape sequence in strings on JavaScript. For example, I can write \\ and it means \. But I don't want to use a escape sequence.
I know that on C# I can write #"My string" and I don't need to escape anything. Is there similar syntax in JavaScript?
No, there's not. However, there are RegExp literals:
/foo\s+bar/
There is no such syntax, but there is a work around:
var string = (<r><![CDATA[
Now you can put a whole lot of stuff here.
Including new lines, and all sorts of symbols: \ " '
]]></r>).toString();
Because it's so verbose it's only worth using this when you have something that would be otherwise unreadable (eg: a pretty long string with a bunch of characters that need escaping).
Related
I need to concatenate untrusted* data into a javascript string, but I need it to work for all types of strings (single quoted, double quoted, or backtick quoted)
And ideally, I need it to work for multiple string types at once
I could use string replace, but this is usually a bad idea.
I was using JSON.stringify, but this only escapes double quotes, not single or backtick.
Other answers that I've found deal with escaping only a single type of quote at a time (and never backticks).
An example of what I need:
untrustedData = 'a String with \'single quotes\', \"double quotes\" and \`backticks\` in it';
const someJS = `console.log(\`the thing is "${escapingFunctionHere(untrustedString)}"\`)`
someJS will be passed to new Function
* N.B. In my context "untrusted" here doesn't mean potentially malicous, but it does need to cope with quotes, escapes and the like.
I am building javascript code dynamically, the constructed code will not be in any way web-facing. In fact its likely that I am the only one who will use this tool directly or indirectly.
I am happy to accept the minimal associated risks
NOTE TO OTHERS: Be sure you understand the risks before doing this kind of thing.
For those interested, I am writing a parser creator. Given an input ebnf grammar file, it will output a JS class that can be used to parse things.
I really do need to output code here.
If all you need to do is escape single quotes ', double quotes " and backticks `, then using replace to prepend a backslash \ should be enough:
untrustedData.replace(/['"`]/g, '\\$&')
const untrustedData = 'I \'am\' "a `string`"';
console.log(untrustedData);
const escapedData = untrustedData.replace(/['"`]/g, '\\$&');
console.log(escapedData);
I have the following function:
function replace(path) {
return path.replace(/\//g, '.').replace(/^\./, '');
};
Can you please explain what exactly is doing? I have some hard time understanding it mostly because of the slashes and escapes.
I know it replaces something with something. :)
return path.replace(/\//g, '.').replace(/^\./, '');
The / at the start and end are delimiters of regex.
The \ inside it will escape the following character(\ and .).
/\//g: Will find all(g: global flag) the / in the string and will replace it by .
/^\./: Will find the . at the start(^) of the string and will remove it
Replace / with ., and then replace . at the beginning of string with an empty string.
Let's assume that path is a string. strings in javascript, like everything else, are objects. Among other things, they have a replace function. You can read about it here.
Those things with the slashes are called regular expressions, or RegExs for short. You can read about them here and here. They are very useful and often used for manipulating strings with operations like replace.
I have been browsing lots of solutions, but somewhy haven't got anything to work.
I need to replace following string: "i:0#.w|dev\\tauri;" with "i:0#.w|dev\tauri;"
I have tried following JS codes to replace:
s.replace(/\\\\/g, "\\$1");
s.replace(/\\\\/g, "\\");
But have had no result. Yet following replaced my \\ with "
s.replace(/\\/g, "\"");
To be honset, then I am really confused behind this logic, it seems like there should be used \\\\ for double backshashed yet it seems to work with just \\ for two backshashes..
I need to do this for comparing if current Sharepoint user (i:0#.w|dev\tauri) is on the list.
Update:
Okay, after I used console.log();, I discovered something interesting.
Incode: var CurrentUser = "i:0#.w|dev\tauri"; and console.log(): i:0#.w|dev auri...
C# code is following:
SPWeb theSite = SPControl.GetContextWeb(Context);
SPUser theUser = theSite.CurrentUser;
return theUser.LoginName;
JavaScript strings need to be escaped so if you are getting a string literal with two back slashes, JavaScript interprets it as just one. In your string you are using to compare, you have \t, which is a tab character, when what you probably want is \\t. My guess is that wherever you are getting the current SharePoint user from, it is being properly escaped, but your compare list isn't.
Edit:
Or maybe the other way around. If you're using .NET 4+ JavaScriptStringEncode might be helpful. If you're still having problems it might help to show us how you are doing the comparison.
I have the following Javascript code to obtain the inner string from an RegExp:
Function.prototype.method = function (name,func){
this.prototype[name] = func;
return this;
};
RegExp.method('toRawString', function(){
return this.toString().replace(/^.(.*).$/,"$1");
});
The purpose of this, is to avoid in string double quoting. For example, if you have a Windows file path "C:\My Documents\My Folder\MyFile.file", you can use it like the following:
alert(/C:\My Documents\My Folder\MyFile.file/.toRawString());
However it is not working for ""C:\My Documents\My Folder\" since it causes syntax error. The only way to avoid it is to keep double quoting at the end of the string. Thus it will be written
alert(/C:\My Documents\My Folder\\/.toRawString());
The fact is any odd number of back slashes on the end of the string will be an error, so all ending back slashes must be double escaped. It will not be hard to use a multiple line small implementation, but are there any single RegExp solution?
NOTE
When using toRawString the RegExp object for this is usually NOT going to be used for any other purpose except for that method. I just want to use the syntax of RegExp to avoid double back slashes in source code. Unfortunately the ending double slashes cannot be easily avoid. I think another workaround is to force a space at the end but that is another question then.
UPDATE
I finally solved the "another question" and posted the code here.
OK, I get what you're trying to do! It's hacky : )
Try something like:
return this.toString().slice(1, -1).replace(/\\+$/, '\\')
Hope that helps.
If you want to include the double quotes in the string just wrap it with single quotes.
s = '"C:\\My Documents\\My Folder\\MyFile.file"'
console.log(s) // Output => "C:\My Documents\My Folder\MyFile.file"
This produces a syntax error:
/C:\My Documents\/
But that regular expression could be written correctly like this:
/C:\\My Documents\\/
Or like this:
new RegExp("C:\\\\My Documents\\\\")
I think your function is just fine and is returning a correct result. Regular expressions just can't end with an unpaired backslash. It's not that you're double escaping - you're just escaping the escape character.
This would produce an error too:
new RegExp("C:\\My Documents\\")
A regular expression like this, for instance, can't be written without a pair of backslashes:
/C:\\What/
Without the second backslash, \W would be interpreted as a special character escape sequence. So escaping the escape character isn't only necessary at the end. It's required anywhere it might be interpreted as the beginning of an escape sequences. For that reason, it might be a good rule of thumb to always use two backslashes to indicate a backslash literal in a regular expression.
Here is a section of code used by CKEditor on my website:
CKEDITOR.config.IPS_BBCODE = {"acronym":{"id":"8","title":"Acronym","desc":"Allows you to make an acronym that will display a description when moused over","tag":"acronym","useoption":"1","example":"[acronym='Laugh Out Loud']lol[/acronym]", ...
If you scroll to the right just a little, you will see this:
"[acronym='Laugh Out Loud']lol[/acronym]"
I need to store all of the CKEditor code inside a javascript string, but I can't figure out how to do it because the string has both " and ' in it. See the problem? Furthermore, I don't think I can just escape the quotes because I tried doing that and the editor didn't work.
Any idea what I can do?
You might try taking the string and injecting JavaScript escape codes into it. JavaScript can essentially use any unicode value when using the format: \u#### - so, for a ' character, the code is \u0039, and for the " character, the code is \u0034.
So - you could encode your example portion of the string as:
\u0034[acronym=\u0039Laugh Out Loud\u0039]lol[/acronym]\u0034
Alternatively, you could attempt to simply escape the quotes as in:
\"[acronym=\'Laugh Out Loud\']lol[/acronym]\"
The problem here occurs when you wind up with this kind of situation:
"data:{'prop1':'back\\slash'}"
Which, when escaped in this manner, becomes:
"data:{\'prop\':\'back\\\\slash\'}\"
While this is somewhat more readable than the first version - de-serializing it can be a little tricky when going across object-spaces, such as a javascript object being passed to a C# parser which needs to deserialize into objects, then re-serialize and come back down. Both languages use \ as their escape character, and it is possible to get funky scenarios which are brain-teasers to solve.
The advantage of the \u#### method is that only JavaScript generally uses it in a typical stack - so it is pretty easy to understand what part should be unescaped by what application piece.
hmm.. you said you already tried to escape the quotes and it gave problems.
This shouldn't give problems at all, so try this:
$newstring = addslashes($oldstring);
There's no need to use Unicode escape sequences. Just surround your string with double quotes, and put a backslash before any double quotes within the string.
var x = "\"[acronym='Laugh Out Loud']lol[/acronym]\"";