1.使用正则的方法
function myTrim(str: string) {
return str.replace(/^\s+|\s+$/g, "");
}
console.log(myTrim(" hello wold "));
解释:
- 正则表达式
^\s+匹配开头的空白字符; \s+$匹配结尾的空白字符;g表示全局替换;replace()会将匹配到的内容替换为空字符串。
2.使用 trimStart() 和 trimEnd() 组合
function myTrim(str: string) {
return str.trimStart().trimEnd();
}
console.log(myTrim(" hello wold "));
String 的 trimEnd() 方法会从字符串的结尾移除空白字符,并返回一个新的字符串,而不会修改原始字符串。trimRight() 是该方法的别名。
const greeting = " Hello world! ";
console.log(greeting);
// Expected output: " Hello world! ";
console.log(greeting.trimEnd());
// Expected output: " Hello world!";
String 的 trimStart() 方法会从字符串的开头移除空白字符,并返回一个新的字符串,而不会修改原始字符串。trimLeft() 是该方法的别名。
const greeting = " Hello world! ";
console.log(greeting);
// Expected output: " Hello world! ";
console.log(greeting.trimStart());
// Expected output: "Hello world! ";
3.trim()
String 的 trim() 方法会从字符串的两端移除空白字符,并返回一个新的字符串,而不会修改原始字符串。
要返回一个仅从一端修剪空白字符的新字符串,请使用 trimStart() 或 trimEnd()。
const greeting = " Hello world! ";
console.log(greeting);
// Expected output: " Hello world! ";
console.log(greeting.trim());
// Expected output: "Hello world!";
4.chart() 和substring()
function myTrim2(str: string) {
var start = 0; //开始索引
var end = str.length - 1; //结束索引
while (start < end && str.charAt(start) == " ") {
start++;
}
while (start < end && str.charAt(end) == " ") {
end--;
}
return str.substring(start, end + 1); //左闭右开
}
console.log(myTrim2(" hello wold "));
String 的 charAt() 方法返回一个由给定索引处的单个 UTF-16 码元构成的新字符串。
const sentence = "The quick brown fox jumps over the lazy dog.";
const index = 4;
console.log(`The character at index ${index} is ${sentence.charAt(index)}`);
// Expected output: "The character at index 4 is q"
String 的 substring() 方法返回该字符串从起始索引到结束索引(不包括)的部分,如果未提供结束索引,则返回到字符串末尾的部分。
const str = "Mozilla";
console.log(str.substring(1, 3));
// Expected output: "oz"
console.log(str.substring(2));
// Expected output: "zilla"

3948

被折叠的 条评论
为什么被折叠?



