I want to get the characters after @ symbol till a space character.
for eg. if my string is like hello @world. some gibberish.@stackoverflow
. Then I want to get the characters 'world' and 'stackoverflow'.
Here is what I have been trying.
var comment = 'hello @world. some gibberish.@stackoverflow';
var indices = [];
for (var i = 0; i < comment.length; i++) {
if (comment[i] === "@") {
indices.push(i);
for (var j = 0; j <= i; j++){
startIndex.push(comment[j]);
}
}
}
I can get the occurences of @ and spaces and then trim that part to get my content but I'd like a better solution / suggestion for this, with without REGEX. Thanks in advance.
The includes() method returns true if a string contains a specified string. Otherwise it returns false .
There are three ways to compare String in Java: By Using equals() Method. By Using == Operator. By compareTo() Method.
If you need to know if a string matches a regular expression RegExp , use RegExp. prototype. test() . If you only want the first match found, you might want to use RegExp.
You can use this regex:
/@(\S+)/g
and grab captured groups using exec
method in a loop.
This regex matches @
and then \S+
matches 1 or more non-space characters that are grouped in a captured group.
Code:
var re = /@(\S+)/g;
var str = 'hello @world. some gibberish.@stackoverflow';
var m;
var matches=[];
while ((m = re.exec(str)) !== null) {
matches.push(m[1]);
}
document.writeln("<pre>" + matches + "</pre>");
PS: Note you will need to use
/@([^.\s]+)/g
if you don't want to capture DOT after word
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With