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".

3
  • 2
    name = name.replace(/jon/i, "hans"); - no quotes. Commented Jun 1, 2017 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. Commented Jun 1, 2017 at 13:29
  • Possible duplicate of How to replace all occurrences of a string in JavaScript? Commented Jun 1, 2017 at 14:09

4 Answers 4

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>

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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

Comments

0

You need to use the regex expression without ""

var name = "jon snow"

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

$("#output").html(name);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.