I'm debugging some code and have found the following code snippet and just don't get what it does:
function appendModelPrefix(value, prefix) {
if (value.indexOf("*.") === 0) {
value = value.replace("*.", prefix);
}
return value;
}
What does my value string has to look like to get validated by the if-condition? And to what does "*." exactly do? I don't get the wildcard...
I'm debugging some code and have found the following code snippet and just don't get what it does:
function appendModelPrefix(value, prefix) {
if (value.indexOf("*.") === 0) {
value = value.replace("*.", prefix);
}
return value;
}
What does my value string has to look like to get validated by the if-condition? And to what does "*." exactly do? I don't get the wildcard...
Share Improve this question asked Dec 15, 2011 at 16:50 knut67knut67 233 bronze badges 2- I could be wrong but i think its checking the value and if nothing appears before the "." than it fills it in with a prefix – Drewdin Commented Dec 15, 2011 at 16:52
- This should help you understand what the code does: jsfiddle/fuAwb – Ivan Commented Dec 15, 2011 at 16:54
6 Answers
Reset to default 3I doesn't wildcard. It searches for and then replaces a literal "*."
by prefix
indexOf
finds the first occurence of "*."
in the string:
>>>"aaa*.".indexOf("*.")
3
So your consition will succeed if the string starts with a "*." (index 0)
>>> "*.aaa".indexOf("*.")
0
The replace method will then replace this first occurence of "*." with the chosen prefix
>>> "*.*.".replace("*.", "z")
"z*."
BTW, you only get wildcard replacements if you use regexes instead of string patterns:
>>> 'abbbc'.replace(/b+/, 'z')
"azc"
indexOf will give the position of the text inside the string.
So the if statement reads if value
starts with "*." then replace it with prefix
If the string starts with the substring *.
, then replace it with prefix
.
>>> "*.".indexOf('*.')
0
>>> "a*.".indexOf('*.')
1
If your value
starts with *.
, then it replaces the *.
by the prefix
parameter.
There is no wilcard-thing in javascript .indexOf()
.
It simply is replacing the value *.
by prefix
.
Its a vanilla string match, if value
begins with *.
then the *.
is replaced by the string in prefix
"aaa" -> "aaa"
"*.a" -> "a" + prefix