OneCompiler

[Javascript] How can I check if a string is started with another string?

I want to check if a string is started with a particular string or character, for example, I want to check if a string starts with $. How can I do that in Javascript?

1 Answer

4 years ago by

Use either startsWith() or extract the substring from the start and match with the substring as shown below

let str = "$Hello world";
let strString ='$'
console.log(str.startsWith(strString));

console.log(str.substr(0,strString.length) === strString);

Run here https://onecompiler.com/javascript/3xns73x7v

4 years ago by Meera