It seems like what you are looking for is txt.substring(0, subtxt.length) === subtxt. In other words, does the search string subtxt match the beginning of the txt string.
function match(txt, subtxt) {
return txt.substring(0, subtxt.length) === subtxt;
}
Test
> txt = "This is Regex";
> ["This", "Th", "This is", "This is Reg", "This is Regex", "Tis", "is", "Reg"]
.forEach(function(sub) {
console.log('"'+sub+'"', "--", match(txt, sub) ? "Valid" : "InValid");
})
"This" -- Valid
"Th" -- Valid
"This is" -- Valid
"This is Reg" -- Valid
"This is Regex" -- Valid
"Tis" -- InValid
"is" -- InValid
"Reg" -- InValid
ES6's startsWith
In ES6, you could use the new String#startsWith method.
In the polyfill given in the above page, they suggest using indexOf, as in
function match(txt, subtxt) {
return !txt.indexOf(subtxt);
}
and indeed that seems that it could be faster than extracting the leading part of the string and doing a full string comparison.
But I really wanted a regexp
If for some reason you really want to do this with a regexp, then try
var regexp = /^T(h(i(s( (i(s( (R(e(g(e(x)?)?)?)?)?)?)?)?)?)?)?)?$/
This regexp can be "read aloud" as
It starts with a 'T' followed by either nothing or an 'h' followed by either nothing or an 'i' followed by either nothing or an 's' followed by....".
You get the idea.
function match1(subtxt) {
return regexp.test(subtxt);
}
Test
> ["This", "Th", "This is", "This is Reg", "This is Regex", "Tis", "is", "Reg"]
.forEach(function(sub) {
console.log('"'+sub+'"', "--", match1(sub) ? "Valid" : "InValid");
})
"This" -- Valid
"Th" -- Valid
"This is" -- Valid
"This is Reg" -- Valid
"This is Regex" -- Valid
"Tis" -- InValid
"is" -- InValid
"Reg" -- InValid
Creating the regexp programatically
If you want to automatically turn your string into a regexp which behaves the way you want, although this seems completely pointless, you could do
function make_regexp(str) {
function _make_regexp(str) {
return str && str[0] + "(" + _make_regexp(str.slice(1)) + ")?";
}
return RegExp("^" + _make_regexp(str) + "$");
}
> make_regexp("This is Regex")
/^T(h(i(s( (i(s( (R(e(g(e(x()?)?)?)?)?)?)?)?)?)?)?)?)?$/