Single Backslash to double backslash Conversion [duplicate] - javascript

This question already has answers here:
JavaScript backslash (\) in variables is causing an error
(5 answers)
Escaping backslash in string - javascript
(5 answers)
Closed 3 years ago.
I want all single backslashes to be converted into double backslash
"C:\Users\MyName\ringtone.mp3" --> "C:\\Users\\MyName\\ringtone.mp3"
But for some reason it returns "C:UsersMyNameingtone.mp3"
So far I have tried the escape() function and the encodeURI() function but they don't work either. Partial of the string comes from nodejs OS Module which only returns with a single backslash on windows (homedir() function).
Here is what I have so far in the function
function normalize(path: string): string {
return path.normalize().replace(/\\/g, '\\');
}
Thanks in Advance

This should work:
var original = 'C:\\Users\\MyName\\ringtone.mp3';
var replaced = original.normalize().replace(/\\/g, '\\\\');
console.log('Original: ' + original);
console.log('Replaced: ' + replaced);
From what I see you had 2 problems:
First, it seems you were initializing your string like this:
var original = 'C:\Users\MyName\ringtone.mp3'
This would make your actual string value C:UsersMyNameingtone.mp3 because a \ character in javascript symbolizes an escape character.
Second, is because the \ character is an escape character, so the '\\' in your replace function is only looking to replace the matching pattern with a single backslash.

Related

How to replace backward slash with forward in js [duplicate]

This question already has answers here:
JavaScript: A BackSlash as part of the string
(3 answers)
Closed 3 years ago.
I'm trying to replace forward slash with backward with below code but the result is not as expected, What's the expected second parameter for replace in this case?
var path = 'C:\Users\abc\AppData\Local\Programs\Python\Python37\python.exe';
path.replace(/\\/g, "/");
console.log(path)
result:
"C:UsersabcAppDataLocalProgramsPythonPython37python.exe"
Your regex is fine but variable declaration needs double backslash because single backslash is interpreted as escape character:
var path = 'C:\\Users\\abc\\AppData\\Local\\Programs\\Python\\Python37\\python.exe';
path = path.replace(/\\/g, "/");
console.log(path);
//=> C:/Users/abc/AppData/Local/Programs/Python/Python37/python.exe
If you want to avoid using \\ in assignment then you can use String.raw
var path = String.raw`C:\Users\abc\AppData\Local\Programs\Python\Python37\python.exe`;
path.replace(/\134/g,"/");
As a regular expression. \134 is the octal representation of a backslash

Switching \n with \\n in javascript [duplicate]

This question already has answers here:
How do I handle newlines in JSON?
(10 answers)
Closed 4 years ago.
So I have a string:
var s = "foo\nbar\nbob";
I want the string to become:
"foo\\nbar\\nbob"
How can I replace every \n with a \\n?
I've tried using some for loops, but I can't figure it out.
A simple .replace would work - search for \n, and replace with \\n:
var s = "foo\nbar\nbob";
console.log(
s.replace(/\n/g, '\\\n')
// ^^ double backslash needed to indicate single literal backslash
);
Note that this results in "a single backslash character, followed by a literal newline character" - there will not be two backslashes in a row in the actual string. It might be a bit less confusing to use String.raw, which will interpret every character in the template literal literally:
var s = "foo\nbar\nbob";
console.log(
s.replace(/\n/g, String.raw`\
`) // template literal contains one backslash, followed by one newline
);

Remove excessive blank lines [duplicate]

This question already has answers here:
Why do regex constructors need to be double escaped?
(5 answers)
Closed 4 years ago.
Here is an attempt to remove any excessive blank lines in string.
I'm trying to understand why second approach doesn't workfor lines which contains whitespace.
Demo.
var string = `
foo
bar (there are whitespaced lines between bar and baz. I replaced them with dots)
....................
.......................
...........
baz
`;
// It works
string = string.replace(/^(\s*\n){2,}/gm, '\n');
// Why it doesn't work?
var EOL = string.match(/\r\n/gm) ? '\r\n' : '\n';
var regExp = new RegExp('^(\s*' + EOL + '){2,}', 'gm');
string = string.replace(regExp, EOL);
alert(string);
Your \s needs to be changed to \\s. Just putting \s is the same as s.
In strings (enclosed in quotes), the backslash has a special meaning. For example, \n is the newline character. There are a couple of others that you may or may not have heard of, e.g. \b, \t, \v. It would be bad language design choice to make only a few defined ones special, and consider the non-existent \s to be an actual backslash and an s, because it would be inconsistent, a source of errors, and not future-proof. That's why, when you want to have a backslash in a string, you escape the backslash to \\.
In your first example, you use / characters to delimit the regular expression. This is not considered a string bound by the above rules.

Why have two '\' in Regex? [duplicate]

This question already has answers here:
Why do regex constructors need to be double escaped?
(5 answers)
Extra backslash needed in PHP regexp pattern
(4 answers)
Regex to replace single backslashes, excluding those followed by certain chars
(3 answers)
Closed 7 years ago.
function trim(str) {
var trimer = new RegExp("(^[\\s\\t\\xa0\\u3000]+)|([\\u3000\\xa0\\s\\t]+\x24)", "g");
return String(str).replace(trimer, "");
}
why have two '\' before 's' and 't'?
and what's this "[\s\t\xa0\u3000]" mean?
You're using a literal string.
In a literal string, the \ character is used to escape some other chars, for example \n (a new line) or \" (a double quote), and it must be escaped itself as \\. So when you want your string to have \s, you must write \\s in your string literal.
Thankfully JavaScript provides a better solution, Regular expression literals:
var trimer = /(^[\s\t\xa0\u3000]+)|([\u3000\xa0\s\t]+\x24)/g
why have two '\' before 's' and 't'?
In regex the \ is an escape which tells regex that a special character follows. Because you are using it in a string literal you need to escape the \ with \.
and what's this "[\s\t\xa0\u3000]" mean?
It means to match one of the following characters:
\s white space.
\t tab character.
\xa0 non breaking space.
\u3000 wide space.
This function is inefficient because each time it is called it is converting a string to a regex and then it is compiling that regex. It would be more efficient to use a Regex literal not a string and compile the regex outside the function like the following:
var trimRegex = /(^[\s\t\xa0\u3000]+)|([\u3000\xa0\s\t]+$)/g;
function trim(str) {
return String(str).replace(trimRegex, "");
}
Further to this \s will match any whitespace which includes tabs, the wide space and the non breaking space so you could simplify the regex to the following:
var trimRegex = /(^\s+)|(\s+$)/g;
Browsers now implement a trim function so you can use this and use a polyfill for older browsers. See this Answer

Javascript Unicode Escaping Backslash [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I decode a string with escaped unicode?
I'm having a javascript variable, in which i have stored a unicode character.
var value = "\\u53d3\\u5f13\\";
I'm adding the above value dynamically to a div, due to the extra back slash(\\u) proper unicode value is not shown. But if I Change it to single back slash that is \u instead of \\u . The unicode symbol is correctly shown.
In my environment I can not store the value with single back slash. As the response is from the server side..
Is there anyway to replace the double backslash with single backslash to show the proper unicode?
Thanks in Advance
It's not about backslash anymore, it's about what the string literally contains. If you just replaced backslashes, you would just end up with "u53d3u5f13". You can trivially unescape them though (if you don't care that anything \uXXXX will be replaced):
function unescapeUnicode( str ) {
return str.replace( /\\u([a-fA-F0-9]{4})/g, function(g, m1) {
return String.fromCharCode(parseInt(m1, 16));
});
}
var value = "\\u53d3\\u5f13\\";
unescapeUnicode(value);
"叓弓\"

Categories