str.indexOf(substr) == 0
str.slice(0, 10) == substr
Which one of the above two is better? Is there any better way?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The performance of the first depends on the length of the string
stras it requires scanning the entire string. Ifstris large it could take a long time to find whether or not the substring is contained within it.If your input string could be large prefer the second.
Another option is:
This avoids scanning the entire string and avoids creating a temporary string.
If performance matters, I’d suggest measuring it for your specific data.