Trufa
Trufa

Reputation: 40717

What seems to be a correct regex doesn't work in replace function

I am trying to match three consecutive dots (".") followed optionally by a space.

My idea was the following:

\.\.\.\s?

Tested it here and seems to do exactly as expected.

But then when I try to use it in the replace function with javascript it doesn't seem to work, it's quite weird unless I'm missing something silly:

replace("\.\.\.\s?", "")

Doesn't work, see live demo here.

What am I missing?

Upvotes: 0

Views: 56

Answers (4)

Anachronous
Anachronous

Reputation: 21

The first parameter of String.replace must be a RegExp object, not String. Change it to:

$('div').text("... hi".replace(/\.\.\.\s?/, ""));

Or,

$('div').text("... hi".replace(new RegExp("\\.\\.\\.\\s?"), ""));

Upvotes: 2

akonsu
akonsu

Reputation: 29536

this should work $('div').text("... hi".replace(/\.\.\.\s?/, ""));

String.replace() takes either a string or a regular expression as the first argument. If it is a string then it is searched for verbatim. https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/String/replace

Upvotes: 3

Bob Gilmore
Bob Gilmore

Reputation: 13758

The regex shouldn't be in quotes. Try...

mystr.replace(/\.\.\.\s?/, "")

jsfiddle

Upvotes: 3

arb
arb

Reputation: 7863

$('div').text("... hi".replace(/\.{3}/gi, ""));

Slightly optimized regular expression.

Upvotes: 1

Related Questions