Christian Moen
Christian Moen

Reputation: 1301

Remove & characters with regex in javascript

I'm a bit stuck on a issue i'm having with regex

This is my string: &Biblioteks&klasse &Test something & something

This is my expected result: Biblioteksklasse Test something & something

This is my actual result: Biblioteksklasse Test something something

Here is my regrex: /^&|(?=\D)&/

Anyone knows how I can get to my actual result?

Upvotes: 0

Views: 81

Answers (3)

Poul Bak
Poul Bak

Reputation: 10929

You can use this simple regex:

&(?=\w)

It matches an '&' and looks ahead to ensure it's followed by a Word character.

Then you replace with an empty string.

How to use:

var text = '&Biblioteks&klasse &Test something & something';
var regex = /&(?=\w)/g;
var output = regex.replace(text, '');

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626747

You seem to want to remove & if it is next to a word char.

In this case, use

s.replace(/&\b|\b&/g, '')

See this regex demo. &\b matches & that is followed with a word char (letter, digit or _) and \b& matches & that is preceded with a word char.

If you plan to remove it when it is next to a non-whitespace char, use

s.replace(/&(?=\S)|(\S)&/g, '$1')

See this regex demo. It matches:

  • &(?=\S) - a & that is followed with a non-whitespace char
  • | - or
  • (\S) - Group 1 (later referred to with $1 from the replacement pattern): any non-whitespace char
  • & - a & char.

Upvotes: 2

Rolvernew
Rolvernew

Reputation: 709

Using a lookbehind you could write:

/(&(?=\w)|(?<=\w)&)/

Upvotes: 1

Related Questions