JS API 笔记

目录

1. JSON

1.1. JSON.stringify

1.1.1. 定义

MDN

stringify(value: any, replacer?: (this: any, key: string, value: any) => any, space?: string | number): string;

stringify(value: any, replacer?: (number | string)[] | null, space?: string | number): string;

1.1.2. 指定需要序列化的字段

const person = {
    name: "Xiaomi",
    age: 10,
    wife: {
        gender: 'female'
    }
}
console.log(JSON.stringify(person, ["name", "wife", "gender"]))
{"name":"Xiaomi","wife":{"gender":"female"}}

1.1.3. 替换字段值

const person = {
    name: "Xiaomi",
    age: 18
}
console.log(
    JSON.stringify(person, (k, v) => {
        if (k == 'name') {
            return 'no name'
        }
        return v
    })
)
{"name":"no name","age":18}

1.1.4. 添加缩进

const person = {
    name: "Xiaomi",
    wife: {
        name: "Xiaoli"
    }
}
console.log(JSON.stringify(person, null, 4))
{
    "name": "Xiaomi",
    "wife": {
        "name": "Xiaoli"
    }
}

1.1.5. 覆盖 stringify 的值

const person = {
    name: "Xiaomi",
    // add this
    toJSON(){
        return "warning"
    }
}
console.log(JSON.stringify(person))
"warning"

2. String

2.1. String.prototype.replace

2.1.1. 定义

MDN

replace(searchValue: { [Symbol.replace](string: string, replaceValue: string): string; }, replaceValue: string): string;

replace(searchValue: { [Symbol.replace](string: string, replacer: (substring: string, ...args: any[]) => string): string; }, replacer: (substring: string, ...args: any[]) => string): string;

2.1.2. 全局替换

const str = "liming.mingli";
console.log(str.replace(/li/g, ""))
ming.ming

2.1.3. 重复左右两侧的值

$&: 查询的字符串 $`: 查询字符串左侧的值 $': 查询字符串右侧的值

const str = "1234-6789"
console.log(str.replace(/-/, "$`$&$'"))
12341234-67896789

2.1.4. 互换匹配字符位置

$1: 第一个匹配组 $n: 第n个匹配组

const str = "[desc](link)"
console.log(str.replace(/\[(.+?)\]\((.+?)\)/, "[$2]($1)"))
[link](desc)

2.1.5. 将单词首字母换成大写

const str = `This method does not mutate the string value it's called on`
console.log(
    str.replace(/\b(\w+)\b/g, (match, p1) => {
        return p1[0].toUpperCase() + p1.substring(1)
    })
)
This Method Does Not Mutate The String Value It'S Called On

2.1.6. 将句子首字母换成大写

const str = `poetry is the other way of using language. perhaps in some hypothetical beginning of things it was the only way of using language or simply was language tout court, prose being the derivative and younger rival. `
console.log(
    str.replace(/(?:^|(?:[.!?]\s))(\w+)/g, (match, p1) => {
        return match.replace(p1, p1[0].toUpperCase() + p1.substring(1))
    })
)
Poetry is the other way of using language. Perhaps in some hypothetical beginning of things it was the only way of using language or simply was language tout court, prose being the derivative and younger rival. 

日期: 2022-11-14

Created: 2022-11-22 Tue 15:00

Validate