Javascript regexp backslash removal query - javascript

I was looking at the responses to the question at Removing backslashes from strings in javascript
and found that both the responses work,
string.replace(/\\\//g, "/");
and
str = str.replace(/\\/g, '');
Could someone please explain the difference between these two and which would be a better choice?

The first one unescapes forward slashes specifically (ie replacing \/ with /)
The second just removes all backslashes.

The second solution str = str.replace(/\\/g, ''); is wrong, because it will remove single \ from the string.

Related

How to replace single backslash with double backslash in Javascript

I have seen a lot of duplicates but none of them works
I spend a day to get this thing up. Gone through all duplicates
I need to replace a single backslash with a double backslash.
I am able to replace all other characters with a double backslash.
console.log("hello & 100\|".replace(/([&%$#_{}])/g, "\\"));
I know that two backslashes is indeed used to make a single backslash.
I tried all the possible ways of using regex as well. But neither works.
Here is another snippet I am using.
var replaceableString = "A\B";
replaceableString = replaceableString.replace(/\\/g, "\\\\");
console.log(replaceableString);
Unfortunately, this also is not working.
Please share if there are any workarounds.
var str = "AAA\\BBB\\CCC\\DDD\\EEE";
var rgx = /\\/g;
var res = str.replace(rgx, "\\\\");
console.log(res);
Comments below questions are very revealing. Single backslash \ is escape character. To obtain single backslash we must use double backslashes. So we must use four backslashes(in reality double) for replace the backslash.

How to Remove double backslashes in a string to Single one?

My string is tel:\\99999999999. How i can replace '\' to '\' single? I want output like: tel:\99999999999.
Please see attached image backslashes not showing into question.
You should escape the slash twice:
"tel:\\99999999999".replace('\\\\', '\\');
You can simply use tel.replace(/\\\\/g, "\\").
Demo:
var tel ="\\99999999999";
console.log(tel.replace(/\\\\/g, "\\"));
You need to escape the \ character with another \, because it's an escape character in JavaScript, you can check JavaScript backslash (\) in variables is causing an error for further reading.
use .replace() to achieve what you want, str.replace("\\\\","\\")
var str = "tel:\\99999999999";
console.log(str.replace("\\\\","\\"))
You can do like this
"tel:\\99999999999".replace('\\\\', '');

JavaScript regex to capture everything after the second to last backslash

I have a regex that looks like the following currently:
/^.*[\\\/]/
This will strip every single backslash from a string. The problem I'm facing is I have to now be able to capture everything from the second to last backslash.
Example:
/Users/foo/a/b/c would return b/c
/Another/example/ would return Another/Example
So I need to capture everything after the second to last backslash. How would the regex above do that?
Try with this simple solution:
s = "aaaa/bbbb/cccc/dddd";
s.split("/").slice(-2).join("/"); /* It will return "cccc/dddd" */
I assume that you mean forward slash, not backslash.
Here is a regex alternative to pierlauro's answer.
/([^\/]+\/[^\/]+)\/?$/
Regex101
As pierlauro's answer shows, split, join, and slice are probably the best options for this. But if you MUST use a regex (not sure why), you could employ something like the following:
\/?(\[^\/\]+?\/\[^\/\]+)\/?$
This regex accommodates for optional trailing slashes and for urls shorter than 2 /s. It leverages the $ character to focus our search scope on the end of the string.

Regex replace linebreak and comma

i've a question about regex, i've a text and it looks like below :
car,model,serie
,Mercedes,324,1,
,BMW,23423,1,
,OPEL,54322,1,
it should look like:
car,model,serie
Mercedes,324,1,
BMW,23423,1,
OPEL,54322,1,
so without commas at the beginning of the text.
What i tried :
var str2 = str.replace(/\n|\r/g, "");
but somehow, i couldn't add comma in regex.
can anyone help me?
Thanks in advance.
There have been a lot of responses to this question and for a newbie to regex it is probably a bit overwelming,
Overall the best response has been:
var str2 = str.replace(/^,/gm, '');
This works by using ^, to check if the first character is a comma and if it is, remove it. It also uses the g and m flags to do this for the first character of every line.
If you are curious about the other versions then read on:
1:
var str2 = str.replace(/^,+/gm, '');
This is a slight variant in that it will remove multiple consecutive commas at the beginning of each line, but based off of your dataset this is not required.
2:
var str2 = str.replace(/\n,/g, '\n');
This version works exactly the same as the first, however it finds each newline follow by a comma with \n, and replaces it with another newline.
3:
var str2 = str.replace(/(\n|\r),/g, '$1')
This version is the same as the previous however it doesn't make the assumption that the newline is a \n, it instead captures any newlines or carriage returns, it works the same as the m flag and ^,.
4:
var str2 = str.replace(/\n+|\r+|,+/g,"\n")
And finally there is this, this is a combination of all the previous regex's, it makes the assumption that you may have a lot mixed newlines and commas without any text, and that you would want to remove all of those characters, it is unnecessary for your examples.
Use this syntax:
str.replace(/^,/gm, '');
You can just use multiline flag and replace leading commas:
str = str.replace(/^,+/gm);
RegEx Demo
Try:
var str2 = str.replace(/(\n|\r),/g, '$1')
Your comma was actually placed outside the regex pattern, so you weren't far off :)

JavaScript regex with escaped slashes does not replace

Do i have to escape slashes when putting them into regular expression?
myString = '/courses/test/user';
myString.replace(/\/courses\/([^\/]*)\/.*/, "$1");
document.write(myString);
Instead of printing "test", it prints the whole source string.
See this demo:
http://jsbin.com/esaro3/2/edit
Your regex is perfect, and yes, you must escape slashes since JavaScript uses the slashes to indicate regexes.
However, the problem is that JavaScript's replace method does not perform an in-place replace. That is, it does not actually change the string -- it just gives you the result of the replace.
Try this:
myString = '/courses/test/user';
myString = myString.replace(/\/courses\/([^\/]*)\/.*/, "$1");
document.write(myString);
This sets myString to the replaced value.
/[\/]/g matches forward slashes.
/[\\]/g matches backward slashes.
Actually, you don't need to escape the slash when inside a character class as in one part of your example (i.e., [^\/]* is fine as just [^/]*). If it is outside of a character class (like with the rest of your example such as \/courses), then you do need to escape slashes.
string.replace doesn't modify the original string. Instead, a returns a new string that has had the replacement performed.
Try:
myString = '/courses/test/user';
document.write(myString.replace(/\/courses\/([^\/]*)\/.*/, "$1"));
Note, that you don't have to escape / if you use new RegExp() constructor:
console.log(new RegExp("a/b").test("a/b"))

Categories

Resources