1

I tried a very simple regular expression.

var name = "jon snow"

name = name.replace("/jon/i", "hans");

$("#output").html(name);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="output"></p>

I simply try to replace "jon" with "hans" by using regular expressions. But It does not work.

Jsfiddle

I informed my selve here.

EDIT: My question is obviously completly different from the "duplicate".

Black
  • 15,426
  • 32
  • 140
  • 232
  • 2
    `name = name.replace(/jon/i, "hans");` - no quotes. – Alex K. Jun 01 '17 at 13:28
  • 1
    When you wrapped your regex in quotes, JS only sees it as a string. Instead of quotes, regular expressions are wrapped (usually) in slashes. – Lix Jun 01 '17 at 13:29
  • Possible duplicate of [How to replace all occurrences of a string in JavaScript?](https://stackoverflow.com/questions/1144783/how-to-replace-all-occurrences-of-a-string-in-javascript) – toesslab Jun 01 '17 at 14:09

4 Answers4

4

Just remove the "" in replace.you are matching the string not the regex pattern

var name = "jon snow"

name = name.replace(/jon/i, "hans");

$("#output").html(name);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="output"></p>
prasanth
  • 21,342
  • 4
  • 27
  • 50
2

You need to remove the quotations; there is a regex literal in JS:

let regex = /jon/i; // this is a regex
let str = "foo"; // this is a string
Luan Nico
  • 4,966
  • 2
  • 30
  • 56
0

When using replace with a regular expression, don't put quotes around the first parameter--just the slashes with the regex options.

0

You need to use the regex expression without ""

var name = "jon snow"

name = name.replace(/jon/i, "hans");

$("#output").html(name);
Daniel Taub
  • 4,511
  • 4
  • 37
  • 67