How to replace single backslash with double backslash in Javascript - 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.

Related

Changing single quotes to double quotes with regular expressions

I am trying to change all single quotes to double quotes in a string (unless the single quote occurs in the middle of a word). Yet my code doesn't work correctly on an example string:
let r = /(\W)'|'(\W)|^'|'$/g;
let s = "'ble' 'bla' aren't"
s.replace(r, "$1\"$2");
What the code returns is:
""ble" 'bla" aren't"
so the opening quote of 'bla" is a single quote. I don't know why that is. Any ideas as to why my solution doesn't work?
Your solution doesn't work because of overlapping. In e' 'b, '(\W) matches '(quote + space), the space is consumed then the following quote (just before b cannot be match because there is no non-word before it.
Replace the single quote only when preceeded or followed by a non-wordboundary:
let r = /\B'|'\B/g;
let s = "'ble' 'bla' aren't"
s = s.replace(r, "\"");
console.log(s);
Since regex is not very flexible, you can try replace multiple times, I can do that by replace 2 times
let r = /([^a-z])'(\w)/g;
let s = "'ble' 'bla' aren't"
s = s.replace(r, "$1\"$2");
s.replace(/(\w)'([^a-z])/g,"$1\"$2");
The proper use of straight double " and single ' quotes do not belong in properly punctuated text -- they are actually used in code. Curly double “ ” and single ‘ ’ quotes (a.k.a. smart quotes) should be used instead. Just going by context provided by example in OP having the need to keep apostrophe means that the text is content and not code:
How is: "'ble' 'bla' aren't"
going to be: ""ble" "bla" aren't" without conflict?
The double quotes within need to be escaped or outer quotes replaced by backticks if the line is within code. If it's just continent then it's probably grammatically incorrect (don't know for sure)?
The following demo will replace straight double and single quotes with their curly/smart counterparts. It replaces a straight single quote with a curly/smart right single quote ’ when its not preceded by a space, ^, |, [, -,—,/,(,\,[,{,", or ] which is a predicate for a closing quote or an apostrophe.
You can remove the statements that you don't need.
let str = document.querySelector('main').innerHTML;
document.querySelector('output').innerHTML = smarten(str);
function smarten(str) {
// Opening single quote
str = str.replace(/(^|[-—/(\[{"\s])'/g, "$1\u2018");
// Closing single quote and apostrophe
str = str.replace(/'/g, "\u2019");
// Opening double quote
str = str.replace(/(^|[-—/(\[{‘\s])"/g, "$1\u201c");
// Closing double quote
str = str.replace(/"/g, "\u201d");
return str;
}
<main>
<p>From Sun Tzu's <i>The Art of War</i>, "If you know both yourself and your enemy, you can win numerous (literally, 'a hundred') battles without jeopardy."</p>
</main>
<output></output>

Javascript: regex escaped space

I have a directory with space on unix, so the space is backslashed. And I need to replace the backslashed space with semicolon. Tried multiple regex'es but not able to find the answer
var str = '/test\ space/a.sh -pqr';
So I am looking to get this after the replace /test;space/a.sh -pqr
console.log("replace: ", str.replace(/\\\s+/g, ";")); //This one doesn't work, (formatting is taking out one backslash)
Your regular expression is correct.
It's your example string that is incorrect - the \ is not properly escaped:
var str = '/test\\ space/a.sh -pqr';
See the fiddle and read more special characters in JavaScript strings.

Javascript regexp backslash removal query

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.

Replacing colon by double backslash

I need to replace : with double backslash \\ but the code below is ignoring one slash.
var original_id = $j(element).attr('id'); // e.g. sub:777
var new_id = original_id.split(":");
new_id = new_id.join("\\:");
alert(new_id);
Instead of displaying sub\\:777, sub\:777 is displayed. The code is ignoring one \ slash.
I would appreciate it if somebody could show me my error.
You must escape the backslashes:
new_id = new_id.join("\\\\:");
See JavaScript Special Characters for some details.
\ is used as an escape character in many languages for things like \n for new line. The reason why you see one is because it is escaped by the first \. (otherwise it would be invisible to you). To remedy this, escape two \s like so: "\\\\:"

How can I put [] (square brackets) in RegExp javascript?

I'm trying this:
str = "bla [bla]";
str = str.replace(/\\[\\]/g,"");
console.log(str);
And the replace doesn't work, what am I doing wrong?
UPDATE: I'm trying to remove any square brackets in the string,
what's weird is that if I do
replace(/\[/g, '')
replace(/\]/g, '')
it works, but
replace(/\[\]/g, ''); doesn't.
It should be:
str = str.replace(/\[.*?\]/g,"");
You don't need double backslashes (\) because it's not a string but a regex statement, if you build the regex from a string you do need the double backslashes ;).
It was also literally interpreting the 1 (which wasn't matching). Using .* says any value between the square brackets.
The new RegExp string build version would be:
str=str.replace(new RegExp("\\[.*?\\]","g"),"");
UPDATE: To remove square brackets only:
str = str.replace(/\[(.*?)\]/g,"$1");
Your above code isn't working, because it's trying to match "[]" (sequentially without anything allowed between). We can get around this by non-greedy group-matching ((.*?)) what's between the square brackets, and using a backreference ($1) for the replacement.
UPDATE 2: To remove multiple square brackets
str = str.replace(/\[+(.*?)\]+/g,"$1");
// bla [bla] [[blaa]] -> bla bla blaa
// bla [bla] [[[blaa] -> bla bla blaa
Note this doesn't match open/close quantities, simply removes all sequential opens and closes. Also if the sequential brackets have separators (spaces etc) it won't match.
You have to escape the bracket, like \[ and \]. Check out http://regexpal.com/. It's pretty useful :)
To replace all brackets in a string, this should do the job:
str.replace(/\[|\]/g,'');
I hope this helps.
Hristo
Here's a trivial example but worked for me. You have to escape each sq bracket, then enclose those brackets within a bracket expression to capture all instances.
const stringWithBrackets = '[]]][[]]testing][[]][';
const stringWithReplacedBrackets = stringWithBrackets.replace(/[\[\]]/g, '');
console.log(stringWithReplacedBrackets);
Two backslashes produces a single backslash, so you're searching for "a backslash, followed by a character class consisting of a 1 or a right bracket, and then you're missing an closing bracket.
Try
str.replace(/\[1\]/g, '');
What exactly are you trying to match?
If you don't escape the brackets, they are considered character classes. This:
/[1\\]/
Matches either a 1 or a backslash. You may want to escape them with one backslash only:
/\[1\]/
But this won't match either, as you don't have a [1] in your string.
I stumbled on this question while dealing with square bracket escaping within a character class that was designed for use with password validation requiring the presence of special characters.
Note the double escaping:
var regex = new RegExp('[\\]]');
As #rudu mentions, this expression is within a string so it must be double escaped. Note that the quoting type (single/double) is not relevant here.
Here is an example of using square brackets in a character class that tests for all the special characters found on my keyboard:
var regex = new RegExp('[-,_,\',",;,:,!,#,#,$,%,^,&,*,(,),[,\\],\?,{,},|,+,=,<,>,~,`,\\\\,\,,\/,.]', 'g')
How about the following?
str = "bla [bla]";
str.replace(/[[\\]]/g,'');
You create a character set with just the two characters you are interested in and do a global replace.
Nobody quite made it simple and correct:
str.replace(/[[\]]/g, '');
Note the use of a character class, with no escape for the open bracket, and a single backslash escape for the close bracket.

Categories

Resources