How can I replace multiple slashes in javascript? - 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.

Related

Javascript substring from last backslash char

This is probably a basic syntax question, but I am not able to find a syntax for a backslash character. Following and other syntaxes that I tried are not accepted for this char.
var fileNameSubstring = data.FileName.substring(data.FileName.lastIndexOf('\') + 1, data.FileName.length);
When defining a string in Javascript you can use the backslash (called escape character) to indicate special characters like new line \n.
To actually have a backslash in your string you should use double blackslash \\.
var fileNameSubstring = data.FileName.substring(data.FileName.lastIndexOf('\\') + 1, data.FileName.length);

Can Someone explain escaping a string in JavaScript

I know this line escapes a javascript string by adding \ before special characters. But can anyone explain how it does that? And also. Can it cause any problems in further string manipulations.
str = str.replace(/[-\\/\\^$*+?.()|[\]{}]/g, '\\$&');
The regular expression replaces anything it matches with backslash and the matched substring. It matches any single characters of the set between [ and ]. That is:
- simple dash
\\ single backslash (preceded by another backslash, because it server as escape character)
/ slash
\\ single backslash again (it is obsolete here)
^, $, *, +, ?, ., (, ), |, [ single characters
\] closing bracket is preceded by escape character, otherwise it would close set of characters to match
{, } single characters
The replacement string \\$& simply says:
\\ add single backslash
$& add the whole substring matched by the expression

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, '');

unterminated string literal in the variable

var MM = '\' + obj[0]['MM '] + '/';
I get two errors while using this code...
missing; before statement and
unterminated string literal
The character \ is "special" because it's used to allow the use of all printable characters in strings. In your case '\' is not a string composed by the only character \, but the beginning of a string starting with the single quote character '.
For exampe if you want the string Hello Andrea "6502" Griffini you can use single quotes
string1 = 'Hello Andrea "6502" Griffini';
and if you want single quotes in the string you can do the opposite
string2 = "Hello Andrea '6502' Griffini";
But what if you want both kind of quotes in the same string? This is where the escape \ character comes handy:
string3 = "'llo Andrea \"6502\" Griffini";
Basically \ before a quote or double quote in a string tells javascript that the following character is just a regular character, with no special meaning attached to it.
Note that the very same character is also used in regular expressions... for example if you want to look for an open bracket [ you must prefix it with a backslash because [ in a regular expression has a special meaning.
The escape is also used to do the opposite... in a string if you put a backslash in front of a normal character you are telling javascript that that character is indeed special... for example
alert("This is\na test");
In the above line the \n sequence means a newline code, so the message displayed will be on two lines ("This is" and "a test").
You may now wonder... what if I need a backslash character in my string? Just double it in that case. In your code for example just use '\\'.
Here is a table for the possible meanings of backslash in strings
\" just a regular double-quote character, it doesn't end the string
\' just a regular single-quote character, it doesn't end the string
\b a backspace character (ASCII code 0x08)
\t a tab character (ASCII code 0x09)
\n a newline character (ASCII code 0x0A)
\v a vertical tab character (ASCII code 0x0B)
\f a form feed character (ASCII code 0x0C)
\r a carriage return character (ASCII code 0x0D)
\033 the character with ASCII code 033 octal = 27 ("ESC" in this case)
\x41 the character with ASCII code 0x41 = 65 ("A" in this case)
\u05D0 the unicode character 0x05D0 (Aleph from the Hebrew charset)
\\ just regular backslash character, not an escape prefix
\ is an escape character. You'll have to double it to literally mean a backslash character, otherwise it'll augment the following character (In this case the next single quote)
You need to properly escape the backslash:
var lastMenstrualPeriod = '\\' + obj[0]['LastMenstrualPeriod'] + '/';
Being escape character, the JS "compiler" is expecting another character to follow, for example \n is newline constant, \t is tab etc.. so \\ is one single backslash in a string.
It is also mentioned in Douglas Crockford book.
You are forgetting to escape '\'
Do this:
var lastMenstrualPeriod = '\\' + obj[0]['LastMenstrualPeriod'] + '/';

Finding Plus Sign in Regular Expression

var string = 'abcd+1';
var pattern = 'd+1'
var reg = new RegExp(pattern,'');
alert(string.search(reg));
I found out last night that if you try and find a plus sign in a string of text with a Javascript regular expression, it fails. It will not find that pattern, even though it exists in that string. This has to be because of a special character. What's the best way to find a plus sign in a piece of text? Also, what other characters will this fail on?
Plus is a special character in regular expressions, so to express the character as data you must escape it by prefixing it with \.
var reg = /d\+1/;
\-\.\/\[\]\\ **always** need escaping
\*\+\?\)\{\}\| need escaping when **not** in a character class- [a-z*+{}()?]
But if you are unsure, it does no harm to include the escape before a non-word character you are trying to match.
A digit or letter is a word character, escaping a digit refers to a previous match, escaping a letter can match an unprintable character, like a newline (\n), tab (\t) or word boundary (\b), or a a set of characters, like any word-character (\w), any non-word character (\W).
Don't escape a letter or digit unless you mean it.
Just a note,
\ should be \\ in RegExp pattern string, RegExp("d\+1") will not work and Regexp(/d\+1/) will get error.
var string = 'abcd+1';
var pattern = 'd\\+1'
var reg = new RegExp(pattern,'');
alert(string.search(reg));
//3
You should use the escape character \ in front of the + in your pattern. eg. \+
You probably need to escape the plus sign:
var pattern = /d\+1/
The plus sign is used in regular expressions to indicate 1 or more characters in a row.
It should be var pattern = '/d\\+1/'.
The string will escape '\\' as '\' ('\\+' --> '\+') so the regex object init with /d\+1/
if you want to use + (plus sign) or $ (sigil /dollar sign), then use \ (backslash) as a prefix. Like that:
\$ or \+

Categories

Resources