简体   繁体   中英

What does string.indexOf(“*.”) do in Javascript?

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 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM