-1

This seems a very simple question but I haven't been able to get this to work.

How do I convert the following string:

var origin_str = "abc/!/!";     // Original string
var modified_str = "abc!!";     // replaced string

I tried this: console.log(origin_str.replace(/\\/,'')); This only removes the first occurrence of backslash. I want to replaceAll. I followed this instruction in SO: How to replace all occurrences of a string in JavaScript?

origin_str.replace(new RegExp('\\', 'g'), '');

This code throws me an error SyntaxError: Invalid regular expression: /\/: \ at end of pattern. What's the regex for removing backslash in javascript.

Community
  • 1
  • 1
Dhawan Gayash
  • 463
  • 1
  • 4
  • 17
  • 4
    `origin_str.replace(/\\/g,'')` – u_mulder Jan 09 '15 at 21:48
  • @u_mulder's comment is correct. use `g` to set the global flag. This parses multiple instances of `/`. http://www.regular-expressions.info/ – Mouser Jan 09 '15 at 21:50
  • 5
    If you're trying to match forward slashes, why are you targeting backslashes ? – adeneo Jan 09 '15 at 21:51
  • @adeneo aren't they the same thing?! – zerkms Jan 09 '15 at 21:53
  • 2
    @zerkms Hmm... /... \... Nope, you're right, absolutely identical. – Niet the Dark Absol Jan 09 '15 at 21:53
  • @zerkms - not in my browser -> **http://jsfiddle.net/sggh8Lje/** ? – adeneo Jan 09 '15 at 22:01
  • @Mouser Can you state why the question got a negative score? – Dhawan Gayash Jan 09 '15 at 23:42
  • @Journeyman yes this is really elementary regular expression work. You can Google it, or find it here on StackOverflow in nearly an instant. I think some people found your question lacking proper research is my guess. – Mouser Jan 09 '15 at 23:46
  • @Mouser Thanks for explaining this to me. I wasn't able to use the RegExp class which was the suggested method in the other SO answers. I am new to Javascript and I felt this is a bit different from PERL, python, java and Bash which is what I am comfortable in. – Dhawan Gayash Jan 10 '15 at 00:40
  • @Journeyman JavaScript has a limited regex engine. It does not support everything that Java does for example. It has, like all languages, its own quirks when it comes to regexes. – Mouser Jan 10 '15 at 00:42

2 Answers2

3

A quick basic overview of regular expressions in JavaScript

When using regular expressions you can define the expression on two ways.

  1. Either directly in the function or variable by using /regular expression/
  2. Or by using the regExp contructor: new RegExp('regular expression').

Please note the difference between the two ways of defining. In the first the search pattern is encapsuled by forward slashes, while in the second one the search pattern is passed as a string.

Remember that regular expressions is in fact a search language with it's own syntax. Some characters are used to define actions: /, \, ^, $, . (dot), |, ?, *, +, (, ), [, {, ', ". These characters are called metacharacters and need to be escaped if you want them to be part of the search pattern. If not they will be treated as an option or generate script errors. Escaping is done by using the backslash. E.g. \\ escapes the second backslash and the search pattern will now search for backslashes.

There are a multitude of options you can add to your search pattern.:

Examples

adding \d will make the pattern search for a numeric value between [0-9] and/or the underscore. Simple regular expressions are parsed from left to right.

/javascript/

Searches for the word javascript in a string.

/[a-z]/

When a pattern is put between square bracket the search pattern searches for a character matching any one of the values inside the square brackets. This will find d in 229302d34330

You can build a regular expression with multiple blocks.

/(java)|(emca)script/

Find javascript or emcascript in a string. The | is the or operator.

/a/ vs. /a+/

The first matches the first a in aaabbb, the second matches a repetition of a until another character is found. So the second matches: aaa.

The plus sign + means find a one or more times. You can also use * which means zero or more times.

/^\d+$/

We've seen the \d earlier and also the plus sign. This means find one or more numeric characters. The ^ (caret) and $ (dollar sign) are new. The ^ says start searching from the begin of the string, while the $ says until the end of the string. This expression will match: 574545485 but not d43849343, 549854fff or 4348d8788.

Flags

Flags are operators and are declared after the regular expression /regular expression/flags JavaScript has three flags you can use:

  • g (global) Searches multiples times for the pattern.
  • i (ignore case) Ignores case in pattern.
  • m (multiline) treat beginning and end characters (^ and $) as working over multiple lines (i.e., match the beginning or end of each line (delimited by \n or \r), not only the very beginning or end of the whole input string)

So a regular expression like this:

/d[0-9]+/ig

matches D094938 and D344783 in 98498D094938A37834D344783.

The i makes the search case-insensitive. Matching a D because of the d in the pattern. If D is followed by one or more numbers then the pattern is matched. The g flag commands the expression to look for the pattern globally or simply said: multiple times.


In your case @Qwerty provided the correct regex:

origin_str.replace(/\//g, "")

Where the search pattern is a single forward slash /. Escaped by the backslash to prevent script errors. The g flags commands the replace function to search for all occurrences of the forward slash in the string and replace them with an empty string "".

For a comprehensive tutorial and reference : http://www.regular-expressions.info/tutorial.html

Community
  • 1
  • 1
Mouser
  • 13,132
  • 3
  • 28
  • 54
  • Good tutorial +1. Scoping is also a major actor in regex. Example `/(java|emca)script/` will match javascript or emcascript. –  Jan 10 '15 at 00:26
  • @sln; Nice I create two groups there, but you can also do it that way. Pff the possibilities are endless :-). That's why I like them. They are almost magic. – Mouser Jan 10 '15 at 00:28
  • Most helpful answer to my question. – Dhawan Gayash Jan 10 '15 at 08:49
1

Looking for this?

origin_str.replace(/\//g, "")

The syntax for replace is

.replace(/pattern/flags, replacement)

So in my case the pattern is \/ - an escaped slash
and g is global flag.

Qwerty
  • 29,062
  • 22
  • 108
  • 136