[英]How to get all values from a javascript array and print in a paragraph tag
[英]how to print all values from an array containing a given string value (JavaScript)
給定一個類似下面代碼的數組:
let words = ['bring','constant','bath','spring','splashing']
如何打印words
數組中帶有ing
字符的所有字符串字符?
您需要使用endsWith
方法來檢查單詞是否以特定值結尾。
let words = ['bring','constant','bath','spring','splashing'] const result = words.filter(w => w.endsWith('ing')) result.forEach(w => console.log(w))
您還可以使用帶有美元符號的正則表達式$
表示以結尾。
let words = ['bring','constant','bath','spring','splashing'] const result = words.filter(w => /(ing)$/.test(w)) result.forEach(w => console.log(w))
由於作者想檢查單詞中間是否存在ing
。 在這種情況下,您可以只使用帶有String.match()
方法的普通正則表達式,最后沒有$
符號。
現場演示:
let words = ['bring','constant','bath','spring','splashing', 'tingtong']; const res = words.filter(word => word.match(/ing/ig)); console.log(res);
或者你也可以通過使用.includes()
方法來實現。
現場演示:
let words = ['bring','constant','bath','spring','splashing', 'tingtong']; const res = words.filter(word => word.includes('ing')); console.log(res);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.