0

How can i do to search if a Javascript String contains the following pattern :

"@aRandomString.temp"

I would like to know if the String contains @ character and then any String and then ".temp" string.

Thanks

1
  • A pattern with a "random string" is not a "specific string" :-) You might fix your title… Commented Oct 2, 2013 at 16:28

4 Answers 4

1

This one liner should do the job using regex#test(Strng):

var s = 'foo bar @aRandomString.temp baz';
found = /@.*?\.temp/i.test(s); // true
Sign up to request clarification or add additional context in comments.

Comments

0

Use indexOf to find a string within a string.

var string = "@aRandomString.temp";
var apos = string.indexOf("@");
var dtemp = string.indexOf(".temp", apos); // apos as offset, invalid: ".temp @"
if (apos !== -1 && dtemp !== -1) {
    var aRandomString = string.substr(apos + 1, dtemp - apos);
    console.log(aRandomString); // "aRandomString"
}

1 Comment

I don't understand (+1), but your solution is a bit complicated :-) Also OP only wants to know whether the match exists, not what the random string is.
0

You can try this

var str = "@something.temp";

if (str.match("^@") && str.match(".temp$")) {

}

demo

1 Comment

The question asks for "contains", not for "is". Also, forgot to escape your regex, and you should use test instead of match
0

You can use the match function. match expects the regular expression.

function myFunction()
{
    var str="@someting.temp"; 
    var n=str.test(/@[a-zA-Z]+\.temp/g);
}

Here is a demo: http://jsbin.com/IBACAB/1

3 Comments

What about the .temp part? Also, use test instead of match.
I have it in the regexp: (/@[a-zA-Z]+\.temp
@Bergi I am assuming that string only contains letters

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.