How to remove forward and backward slashes from string in javascript - javascript

I want to remove all the forward and backward slash characters from the string using the Javascript.
Here is what I have tried:
var str = "//hcandna\\"
str.replace(/\\/g,'');
I also tried using str.replace(/\\///g,''), but I am not able to do it.
How can I do it?

You can just replace \/ or (|) \\ to remove all occurrences:
var str = "//hcandna\\"
console.log( str.replace(/\\|\//g,'') );
Little side note about escaping in your RegEx:
A slash \ in front of a reserved character, is to escape it from it's function and just represent it as a char. That's why your approach \\// did not make sense. You escapes \ with \, so it becomes \\. But if you want to escape /, you need to do it like this too: \/.

You want something more like this:
var str = "//hcandna\\"
str=str.replace(/[\/\\]/g,'');
console.log(str);
This will search for the set of characters containing a forward or backward slash and replace them globally. What you had requires a backslash followed by a forward slash.
Here's the output from Node:
str.replace(/[\/\\]/g,'')
'hcandna'

You need to add the result to a new string like:
var newstr = str.replace(/(\\|\/)+/ig, '');

You can use this code snippet
str.replace(/(\\|\/)/g,'');

Related

Javascript | Can't replace \n with String.replace()

I have code which parse web-site and take information from database.
It's look like this:
var find = body.match(/\"text\":\"(.*?)\",\"date\"/);
As result, I have:
гороскоп на июль скорпион\nштукатурка на газобетон\nподработка на день\nмицубиси тюмень\nсокращение микрорайон
Then i try to replace \n, but it's don't working.
var str = find[1].replace(new RegExp("\\n",'g'),"*");
What I can do with this?
It looks like you want to replace the text \n, i.e. a backslash followed by an n, as opposed to a newline character.
In which case you can try
var str = find[1].replace(/\\n/g, "*");
or the less readable version
var str = find[1].replace(new RegExp("\\\\n", "g"), "*");
In regular expressions, the string \n matches a newline character. To match a backslash character we need to 'escape' it, by preceding it with another backslash. \\ in a regular expression matches a \ character. Similarly, in JavaScript string literals, \ is the escape character, so we need to escape both backslashes in the regular expression again when we write new RegExp("\\\\n", "g").
Working in the console!
Here this works globally and works on both types of line breaks:
find[1].replace(/\r?\n/g, "*")
if you dont want the '\r' to be replaced you could simply remove that from the regex.
removes all 3 types of line breaks
let s = find[1].replace(/(\r\n|\n|\r)/gm, " - ")

Regex for both newline and backslash for Replace function

I am using a replace function to escape some characters (both newline and backslash) from a string.
Here is my code:
var str = strElement.replace(/\\/\n/g, "");
I am trying to use regex, so that I can add more special characters if needed. Is this a valid regex or can someone tell me what am I doing wrong here?
You're ending the regex early with an unescaped forward slash. You also want to use a set to match individual characters. Additionally you might want to add "\r" (carriage return) in as well as "\n" (new line).
This should work:
var str = strElement.replace(/[\\\n\r]/g, "");
This is not a valid regex as the slash is a delimiter and ends the regex. What you probably wanted is the pipe (|), which is an alternation:
var str = strElement.replace(/\\|\n/g, "");
In case you need to extend it in the future it may be helpful to use a character class to improve readability:
var str = strElement.replace(/[\\\nabcx]/g, "");
A character class matches a single character from it's body.
This should work. The regular expression replaces both the newline characters and the backslashes in escaped html text:
var str = strElement.replace(/\\n|\\r|\\/g, '');

How can I replace multiple slashes in javascript?

var str = "Hello\\\World\\\";
var newStr = str.replace("\\\", "");
alert(newStr); // I want this to alert: HelloWorld
The number of slashes is always 3, not more not less. How can I replace them? The code above doesn't work at all. I've played around a bit with the global flag, escaping the slashes etc but can't figure it out.
Firstly, you need to escape each slash with another backslash, as mentioned by #Bathsheba.
Additionally, you want your replacement regex to be global:
var str = "Hello\\\\\\World\\\\\\";
var newStr = str.replace(/\\\\\\/g, "");
alert(newStr); // I want this to alert: HelloWorld
If you want three slashes in a row in a string literal then you need to escape each one in turn:
var str = "Hello\\\\\\World\\\\\\";
var newStr = str.replace("\\\\\\", "");
In your current string, \\\W would be one slash and an error as \W is not a valid sequence. (Some more examples: \\ is a single slash, \t a tab, \" a quotation character).
Try this regex \\\\\\ for replace
\\ indicates \
There are 12 characters with special meanings: the backslash \, the caret ^, the dollar sign $, the period or dot ., the vertical bar or pipe symbol |, the question mark ?, the asterisk or star *, the plus sign +, the opening parenthesis (, the closing parenthesis ), and the opening square bracket [, the opening curly brace {, These special characters are often called "metacharacters".
If you want to use any of these characters as a literal in a regex, you need to escape them with a backslash.

Javascript regex replace single slash in to double slash?

Javascript regex replace single slash into double slash not for replace double slash in a string?
var tempPath ="//DocumentImages//Invoices//USD//20130425//I27566554 Page- 1.tif&//hercimg/IMAGES/2008/20130411/16192144/16192144-10003.tif&";
Here replace all single slash in to double (//) not to all double slash.
like //DocumentImages//Invoices//USD//20130425//I27566554 Page- 1.tif&//hercimg//IMAGES//2008//20130411//16192144//16192144-10003.tif&
This would work assuming your string does not also end in a /
yourString.replace(/\/[^\/]/g,"//")
/stuff/ is just JavaScript regex literal notation
\/ is an escaped "/"
[^\/] is anything but a "/" (again, with escaping)
the "g" on the regex literal means "replace all matches and not just the first"
which we replace for "//" which is what you want.
replace accepts a string and returns a new string with the value changed without changing the original.
Here is a working fiddle
yourString.replace(/([^\/])\/([^\/])/g,"$1//$2")
Could be also helpful:
var s = "http://www.some-url.com//path//to";
var res = s.replace(/(https?:\/\/)|(\/)+/g, "$1$2");

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: "\\\\:"

Categories

Resources