简体   繁体   中英

How to get first unique character in a string after a string search?

I am trying to find if a user enters a username in the content of their post on my new social network. For example: "Happy birthday to @drew he's so cool". I want to be able to search the string for "@", and then 'take apart' the string to get the value of the username. I basically want to end with "@drew".

var n = contentq.search("@");
var newname = contentq.splice(n, /no idea/ )

This is honestly what I have so far. I figured the best way was to find the "@", and then splice the text from the @ to the index of the first space (" "). My question is, how do I get the index of the first space after "@"? Thanks!

You can try using a regex to find the @ and text following it up to the space

var text = "Hello @drew how are you doing?";

function getUserName(text){
    var parsed = /(@.*?)\s/.exec(text);
    if(parsed){
        return parsed[1];
    }
}

console.log(getUserName(text)); //Prints @drew

Edit: This won't catch "Hello @drew" because of the space. Jagsparrows \\w+ would do better

var text = "Hello @drew how are you doing?";

function getUserName(text){
    var parsed = /(@\w+)/.exec(text);
    if(parsed){
        return parsed[1];
    }
}

console.log(getUserName(text)); //Prints @drew

Search for @ then for word regex.

var str = "Happy birthday to @drew he's so cool"
str.match(/@\w+/)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM