3

I've already read all the articles in here which touch a similar problem but still don't get any solution working. In my case I want to wrap each word of a string with a span. The words contain special characters like 'äüö...'

What I am doing at the moment is:

var textWrap = text.replace(/\b([a-zA-Z0-9ßÄÖÜäöüÑñÉéÈèÁáÀàÂâŶĈĉĜĝŷÊêÔôÛûŴŵ-]+)\b/g, "<span>$1</span>");

But what happens is that if the äüñ or whatever NON-Ascii character is at the end or at the beginning it also acts like a boundary. Being within a word these characters don't act as a boundary.

'Ärmelkanal' becomes Ä<span>rmelkanal</span> but should be <span>Ärmelkanal</span>
'Käse'works fine... becomes <span>Käse</span>
'diré' becomes <span>dir</span>é but should be <span>diré</span>

Any advice would be very appreciated. I need to do that on clientside. By the way, did I mention that I hate regular expressions?

Thank You very much!

1 Answer 1

1

The problem is that JavaScript recognizes word boundaries only before/after ASCII letters (and numbers/underscore). Just drop the \b anchors and it should work.

result = subject.replace(/[a-zA-Z0-9ßÄÖÜäöüÑñÉéÈèÁáÀàÂâŶĈĉĜĝŷÊêÔôÛûŴŵ-]+/g, "<span>$&</span>");
Sign up to request clarification or add additional context in comments.

1 Comment

Looks awful ;-) But it works Thank you very very very much!!! And your solution is clever. Thanks for the good explanation!!!

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.