user2305193
user2305193

Reputation: 2059

Regex Javascript: Remove single charcaters in Text

I imagine this question is very simple for experts, yet I can't figure this one out (not even reading through stackoverflow & google):

I want to remove all alphanumeric and umlaut (and double S) single characters (i.e. or if not possible, then surrounded by spaces). Here what I tried:

    var a = "text 0 1 2 3 a 4 text text";
    a = a.replace(/\b\s+[a-zA-Z0-9äöüÄÖÜß]\s+\b/g, ' ')
    a = a.replace(/\s\s+/g, ' ') + "\n" //remove double spaces
    alert(a)

What I get: text 1 3 4 text text Expected output: text text text

see also: Fiddle snippet

edit: updated my try according to comments thanks @stanislav-Šolc

Upvotes: 0

Views: 261

Answers (1)

LukStorms
LukStorms

Reputation: 29677

A positive lookahead (?= ) could help here.

var a = "text 0 ä 1 ë 2 i      text ";
a = a.replace(/ [a-zA-Z0-9äëïöÄËÜÏÖ](?= )/g, '');
a = a.replace(/  +/g, ' ');
alert(a);

The first regex will look for a space and a character, followed by a space.

So it will return :

text text

And if you want to be more thourough about removing single characters then this could be tried:

a = a.replace(/ [^ ](?= )/g, '');

But that could probable remove also stuff you want

Upvotes: 1

Related Questions