Can someone explain me this behaviour? - javascript

Why in the first case there're backslashes while in the second one there is? The escape function shouldn't change anything right? And even if it was the most logic would be str.replace('\'', '\\\'') , so... Thanks in advance.
escape = function(str) {
str = str.replace('\\', '\\\\')
str = str.replace('\'', '\\\'')
str = str.replace('\"', '\\\"')
str = str.replace('\0', '')
str = str.replace('\r', '\\r')
str = str.replace('\n', '\\n')
return str;
}
var original = ("Maura';--");
var escaped = escape("Maura';--");
//var encoded = btoa(escaped);
console.log(original);
console.log(escaped);
//console.log(encoded);
Output:
'Maura';--'
'Maura\';--'

In the first case you are not apply the escape function on the string original. In the second case its changed due to second line of the escape function
str = str.replace('\'', '\\\'')
The above line is same as
str = str.replace("'", '\\\'').
And the second part \\\' will become \'.

Related

How to regex, and add "-" between words?

UPDATED
I been looking around in the old interweb to see if there is any way I can regex this as part of a replace method I'm doing: str.replace(/\w[A-Z]/gm, "-")
thisIsARegex
into this:
this-Is-A-Regex
I tried to mess around on regex101 with matching a \w character followed by [A-Z] but failed.
Any thoughts?
If the first char can't be uppercase:
var str = "thisIsARegex";
str = str.replace(/(?=[A-Z])/g, "-");
console.log(str); // this-Is-A-Regex
If the first char can be uppercase:
var str = "ThisIsARegex";
str = str.replace(/.(?=[A-Z])/g, "$&-");
console.log(str); // This-Is-A-Regex
or
var str = "ThisIsARegex";
str = str.replace(/\B(?=[A-Z])/g, "-");
console.log(str); // This-Is-A-Regex
(Last snippet suggested by #Thomas.)
var s = "thisIsARegex";
s = s.replace(/([A-Z])/g, '-$1').trim();
console.log(s);
Try this one:
you can check regex on this page and make your own tests:
https://regexr.com/
// initial value
let text = "thisIsARegexText";
// select Uppercase characters
let regexPattern = /[^a-z]/g;
// dump temp array
let newText = [];
// go through all characters, find Uppercase and replace with "-UppercaseCharacter"
for(i of text){
newText.push(i.replace(/[^a-z]/g, "-" + i))
}
// assign the result to the initial variable
text = newText.join("");

Javascript regex to add to every character of a string a backslash

So as the title says I'd like to add to every character of a string a backslash, whether the string has special characters or not. The string should not be considered 'safe'
eg:
let str = 'dj%^3&something';
str = str.replace(x, y);
// str = '\d\j\%\^\3\&\s\o\m\e\t\h\i\n\g'
You could capture every character in the string with (.) and use \\$1 as replacement, I'm not an expert but basically \\ will render to \ and $1 will render to whatever (.) captures.
HIH
EDIT
please refer to Wiktor Stribiżew's comment for an alternative which will require less coding. Changes as follows:
str = str.replace(/(.)/g, '\\$1'); for str = str.replace(/./g, '\\$&');
Also, for future reference I strongly advice you to visit regexr.com when it comes to regular expressions, it's helped ME a lot
let str = 'dj%^3&something';
str = str.replace(/(.)/g, '\\$1');
console.log(str);
If you just want to display a string safely, you should just do:
let str = 'dj%^3&something';
let node = document.createTextNode(str);
let dest = document.querySelector('.whatever');
dest.appendChild(node);
And then you are guaranteed that it will be treated as text, and won't be able to execute a script or anything.
For example: https://jsfiddle.net/s6udj03L/1/
You can split the string to an array, add a \ to each element to the array, then joint the array back to the string that you wanted.
var str = 'dj%^3&something';
var split = str.split(""); // split string into array
for (var i = 0; i < split.length; i++) {
split[i] = '\\' + split[i]; // add backslash to each element in array
}
var joint = split.join('') // joint array to string
console.log(joint);
If you don't care about creating a new string and don't really have to use a regex, why not just iterate over the existing one and place a \ before each char. Notice to you have to put \\ to escape the first \.
To consider it safe, you have to encode it somehow. You could replace typical 'non-safe' characters like in the encode() function below. Notice how & get's replaced by &
let str = 'dj%^3&something';
let out = "";
for(var i = 0; i < str.length; i++) {
out += ("\\" + str[i]);
}
console.log(out);
console.log(encode(out));
function encode(string) {
return String(string).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}

Invert brace from { to } and vise versa

I have a string with { and } how can I take all of them and reverse them, so all { become } and } become {?
I can't do this:
str = str.replace("}", "{");
str = str.replace("{", "}");
because that will make A face the same way as B then it will replace B which will all change them to the same direction.
I tried doing this:
str = str.replace(["{", "}"], ["}", "{"]);
But that just doesn't seem to do anything (not even error out).
So, what can I do to invert them?
You could use a regexp with a callback function to solve this:
str.replace(/\{|\}/g, function(match) {
return match == "}" ? "{" : "}";
});
You can use a temporary string that will definitely be unique to do the swap:
str = str.replace("}", "TEMP_HOLDER");
str = str.replace("{", "}");
str = str.replace("TEMP_HOLDER", "{");
But it's prone to a bug if the string contains the temp string and it also doesn't replace more than one occurrence. I'd suggest using Erik's answer.
You need to convert to something else in the first pass, and then convert to what you want after you've made the other conversions.
str = str.replace("{", "_###_");
str = str.replace("}", "{");
str = str.replace("_###_", "}");
Of course, the something else will need to be something that won't otherwise be in your string. You could use "\r\n" if you are sure you string won't contain newlines.
You could go with a two stage solution:
str = str.replace("}", "~");
str = str.replace("{", ",");
str = str.replace("~", "{");
str = str.replace(",", "}");

How to globally replace a forward slash in a JavaScript string?

How to globally replace a forward slash in a JavaScript string?
The following would do but only will replace one occurence:
"string".replace('/', 'ForwardSlash');
For a global replacement, or if you prefer regular expressions, you just have to escape the slash:
"string".replace(/\//g, 'ForwardSlash');
Use a regex literal with the g modifier, and escape the forward slash with a backslash so it doesn't clash with the delimiters.
var str = 'some // slashes', replacement = '';
var replaced = str.replace(/\//g, replacement);
You need to wrap the forward slash to avoid cross browser issues or //commenting out.
str = 'this/that and/if';
var newstr = str.replace(/[/]/g, 'ForwardSlash');
Without using regex (though I would only do this if the search string is user input):
var str = 'Hello/ world/ this has two slashes!';
alert(str.split('/').join(',')); // alerts 'Hello, world, this has two slashes!'
Is this what you want?
'string with / in it'.replace(/\//g, '\\');
This has worked for me in turning "//" into just "/".
str.replace(/\/\//g, '/');
Hi a small correction in the above script..
above script skipping the first character when displaying the output.
function stripSlashes(x)
{
var y = "";
for(i = 0; i < x.length; i++)
{
if(x.charAt(i) == "/")
{
y += "";
}
else
{
y+= x.charAt(i);
}
}
return y;
}
This is Christopher Lincolns idea but with correct code:
function replace(str,find,replace){
if (find){
str = str.toString();
var aStr = str.split(find);
for(var i = 0; i < aStr.length; i++) {
if (i > 0){
str = str + replace + aStr[i];
}else{
str = aStr[i];
}
}
}
return str;
}
Example Usage:
var somevariable = replace('//\\\/\/sdfas/\/\/\\\////','\/sdf','replacethis\');
Javascript global string replacement is unecessarily complicated. This function solves that problem. There is probably a small performance impact, but I'm sure its negligable.
Heres an alternative function, looks much cleaner, but is on average about 25 to 20 percent slower than the above function:
function replace(str,find,replace){
if (find){
str = str.toString().split(find).join(replace);
}
return str;
}
var str = '/questions'; // input: "/questions"
while(str.indexOf('/') != -1){
str = str.replace('/', 'http://stackoverflow.com/');
}
alert(str); // output: "http://stackoverflow.com/questions"
The proposed regex /\//g did not work for me; the rest of the line (//g, replacement);) was commented out.
You can create a RegExp object to make it a bit more readable
str.replace(new RegExp('/'), 'foobar');
If you want to replace all of them add the "g" flag
str.replace(new RegExp('/', 'g'), 'foobar');

Replace comma by double quote in javascript

How to replace comma by double quote in javascript?
For example: "c,C#,JavaScript" should be like "C","C#","JavaScript"
str = '"c,C#,JavaScript"';
str = str.split(',').join('","');
That would result in "c","C#","JavaScript"
var original = '"c,C#,JavaScript"';
var quoted = original.replace(/,/g, '","'); // "c","C#","JavaScript"
Just to toss it in there, you could also .split() and .join(), like this:
var oldString = '"c,C#,JavaScript"';
var newString = oldString.split(',').join('","');
You can test it here.
You can do this:
str = "c,C#,JavaScript";
str = str.replace(/,/g, '"');
Result:
c"C#"JavaScript

Categories

Resources