0

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

3
  • 1
    \s* means zero or more, that is way how you loose all numbers at text. Change \s* to any other multipler, to \s+ fo example, or you can use word boundary (anchor) \b[0-9]\b that will handle even single chars on the end of the line... Commented Jun 5, 2016 at 11:57
  • a.replace('\s{2,}',' ') and a.replace('\s\d\s',' ') Commented Jun 5, 2016 at 12:15
  • @prizm: does not give me the right output Commented Jun 5, 2016 at 12:21

1 Answer 1

1

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

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

2 Comments

reading up on lookaheads, thanks, / [^ ](?= )/g was exactly what I needed. I was looking into word boundaries etc... this is perfect thanks
I actually first should about using a wordboundairy \b. But that doesn't seem to work well with the umluads.

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.