问题描述
该笔记将记录:在 JavaScript 中,与字符串 String 类型有关的操作,以及相关问题处理。
解决方案
定义字符串
const name = 'ram'; const name1 = "hari"; const result = `The names are ${name} and ${name1}`; // 能够在字符串中使用变量
字符串替换
通过正则表达式,来进行字符串替换:
"sttring/".replace(/\/$/, ""); // 替换结尾的 / 字符 // 中文、字母、数字,并移出连续的空格 let str = '就爱仏oqfofa,.- 2+= 撒123ffds' let newStr = str.replace(/[^a-zA-Z0-9\u4e00-\u9fa5]/g, " ") newStr = newStr.replace(/\s+/g, ' ') // 替换全部字符串 strFoo.replaceAll('dog', 'monkey')
字符转义
strFoo.replaceAll("'", "\\'")
提取字符串
通过正则表达式,来提取字符串:
// 我们提取中文、字母、数字 let str = '就爱仏oqfofa,.-+=撒123ffds' let result = str.matchAll(/[a-zA-Z0-9\u4e00-\u9fa5]+/g) let matchAll = Array.from(result) console.log(matchAll) // 我们在正则表达式中使用 + 以保持其连贯,而不是拆成单独字符
参考文献
JavaScript Array length Property
Array is not a data type in Javascript? – Stack Overflow
javascript – Return string without trailing slash – Stack Overflow
Methods of RegExp and String
String.prototype.replaceAll() – JavaScript | MDN