开发者

Find and Replace a substring which has current focus

I am trying to update a substring in textarea. Basically, its a twitter li开发者_StackOverflow社区ke @username feature. User will type in @user and I have to replace "@user.." with user's selected username.

String:

Hello this is test@gmail.com and @gma

In above string, the focus is at the end of string i., after @gma. I would like to replace @gma with my choice of substring. Somehow, I am not able to do it. When I use

this.value = this.value.replace("@gma"+"", "ReplaceText") + ' ';

the @gma of the test@gmail.com is replaced. How do I change the recently typed @gma?

I can get the caret position, but not able to replace the required substring.

Any help would be appreciated.


You'll want to use RegEx instead of a normal string for the replacement.

this.value = this.value.replace(new RegExp("@gma$","g"), "ReplaceText") + ' ';

The important part is the $ sign, which means to search for @gma only at the end of the string. If you want to replace any alphanumeric string after the last @ sign:

this.value = this.value.replace(
    new RegExp("@[A-Za-z0-9]+$","g"), 
    "ReplaceText") 
+ ' ';


If you know the username is always going to be at the end of the string, you can use the regex end of string match $:

value = "Hello this is test@gmail.com and @gma";
var re = new RegExp("@[a-zA-Z_0-9]+$");
value = value.replace(re, 'Replace Text');
console.log(value);
// => "Hello this is test@gmail.com and Replace Text"

Twitter usernames are allowed allowed to contain letters, numbers and underscores.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜