Reputation: 1301
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
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
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