1

I try to wrap string with # hashtag character follow any language , below is my code after I add u shows error Invalid flag supplied to RegExp constructor., how to solve it?

javascript

text.replace(/#([a-z0-9_\pL_]+)/igu, '<a href="'+url+'/$1">@$1</a>');
10
  • That might be because u is not a valid modifier? Commented Apr 29, 2015 at 17:44
  • Uh... by not passing u? JavaScript is Unicode-aware already. Commented Apr 29, 2015 at 17:44
  • but if I remove u only select english character Commented Apr 29, 2015 at 17:45
  • "but if I remove u only select english character" - but if you add u then it doesn't work at all, or select any character; because - as noted - it's both unnecessary and an invalid modifier. Commented Apr 29, 2015 at 17:47
  • 1
    @vibskov check this out.. stackoverflow.com/questions/25968770/… Commented Apr 29, 2015 at 17:52

1 Answer 1

1

Here is an approach that uses the XRegExp library (with the XRegExp Unicode Base add-on):

var hashtags = XRegExp('#([a-z0-9_\\p{L}]+)', 'ig'),
    input = $('#input'),
    output = $('#output'),
    url = 'http://example.com';

input.on('keyup', function() {
    output.text(XRegExp.replace(input.val(), hashtags, '<a href="'+url+'/$1">@$1</a>'));
}).trigger('keyup');
pre {
    white-space: pre-wrap;       /* CSS 3 */
    white-space: -moz-pre-wrap;  /* Mozilla, since 1999 */
    white-space: -pre-wrap;      /* Opera 4-6 */
    white-space: -o-pre-wrap;    /* Opera 7 */
    word-wrap: break-word;       /* Internet Explorer 5.5+ */
}
input {
  width: 98%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xregexp/2.0.0/xregexp-min.js"></script>
<script src="http://xregexp.com/addons/unicode/unicode-base.js"></script>

<label>Input:</label>
<input id='input' value='An example with #日本人 and #English but not #$%!'/><br>
<label>Output:</label>
<pre id='output'></pre>

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

Comments

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.