
字符串和正则表达式
|
61
const
searchString = 'INFINITELY';
const
fullText = 'I know not where I was born, save that the castle was' +
' infinitely old and infinitely horrible.';
if
(fullText.toLowerCase().includes(searchString.toLowerCase())) {
//
找到要搜索的字符串
}
includes()
方法不指明匹配的子串出现在何处。如果你需要这个信息,应该考虑使
用
String.indexOf()
方法,详见
2.11
节。
2.8
替换字符串出现的每一处
2.8.1
问题
你想找到指定子串在字符串中出现的每一处,全部替换掉。
2.8.2
方案
可以使用
String.replaceAll()
方法一次性替换。只需指定要搜索的子串和要替换
的另一个字符串。
const
storyText = 'I know not where I was born, save that the castle was' +
' infinitely old and infinitely horrible.';
const
changedStory = storyText.replaceAll('infinitely', 'somewhat');
console.log(changedStory);
执行这段代码,你会在开发者控制台中看到替换后的字符串,即“ ...