Searching text with regex which is starting with specific pattern

Viewed 32

I am searching the word inside the text using specific keyword.

const matchHashtags = /(#\w+) ?/g;
const text ="this is #sample tag and other #another tag";
while ((hashtag = matchHashtags.exec(text))) {
      alert(hashtag);
}

As in above, we are searching using the word starting with # and it is working fine. But with the below code, I am searching for the text starting with "iphone~".

const matchHashtags2 = /(^|\s)\iphone~(\w+)/g;
const text2 ="I have iphone~seven~new and iphone~seven~ old phones";
while ((hashtag2 = matchHashtags2.exec(text2))) {
      alert(hashtag2);
}

I am expecting this to search for iphone~seven i.e to include next word after iphone~. But this query is returning output as 3 values: "iphone~seven, ,seven".

https://jsfiddle.net/gecj54a3/1/

Please assist in resolving the issues. Thank you!

3 Answers

What´s wrong with const matchHashtags2 = /(iphone~\w+) ?/g;?

I would do something like this:

var text2 = 'I have iphone~seven~new and iphone~seven~old phones';
var myArray2 = text2.split(' ');
for (var i = 0; i < myArray2.length; i++){
    if(myArray2[i].includes('iphone')){
        alert(myArray2[i]);
    }
}

Try this:

const matchHashtags2 = /(^|\s)\iphone~(\w+)/g;
const text2 ="I have iphone~seven~new and iphone~seven~ old phones";
while ((hashtag2 = matchHashtags2.exec(text2))) {
      alert(hashtag2[2]); // hashtag2 is an array
}
Related