简体   繁体   English

如何使用JavaScript从字符串中获取特定文本

[英]How to get specific text from a string using javascript

I am trying to get text from an array except year,month,date using javascript.I do not know how do it. 我正在尝试使用javascript从除年,月,日之外的数组中获取文本。我不知道该怎么做。

 var arr = [ "power-still-rate-19.08.22", "main-still-rate-19.08.22", "oil-power-rate-19.08.22", "oil-mill-rate-19.7.2" ]; var result; for (var i = 0; i < arr.length; i++) { result = arr[i].remove('?????????'); } console.log(result); //result should be like = power-still-rate,main-still-rate,oil-power-rate ; 

Split, slice and join 分割,切片和合并

 var arr = ["power-still-rate-19.08.22", "main-still-rate-19.08.22", "oil-power-rate-19.08.22","oil-mill-rate-19.7.2"]; var result = arr.map(item => item.split("-").slice(0,-1).join("-")) console.log(result); 

Split, pop and join 拆分,弹出并加入

 var arr = ["power-still-rate-19.08.22", "main-still-rate-19.08.22", "oil-power-rate-19.08.22","oil-mill-rate-19.7.2"]; var result = arr.map(item => { let res = item.split("-"); res.pop(); return res.join("-") }) console.log(result); 

No map: 没有地图:

 var arr = ["power-still-rate-19.08.22", "main-still-rate-19.08.22", "oil-power-rate-19.08.22","oil-mill-rate-19.7.2"]; var result = arr.join("").split(/-\\d{1,}\\.\\d{1,}\\.\\d{1,}/); result.pop(); // last empty item, not needed if you do not want an array just join with comma console.log(result); 

Use a regular expression to match non-digit characters from the start of the string, followed by - and a digit: 使用正则表达式匹配字符串开头的非数字字符,后跟-和数字:

 const input = ["power-still-rate-19.08.22", "main-still-rate-19.08.22", "oil-power-rate-19.08.22","oil-mill-rate-19.7.2"]; const output = input.map(str => str.match(/\\D+(?=-\\d)/)[0]); console.log(output); 

Using split on - ,splicing the last element which is the date and joining on - 使用- split on - ,将最后一个元素(即日期) split on -joining on -

 var arr=["power-still-rate-19.08.22","main-still-rate-19.08.22","oil-power-rate-19.08.22"]; arr.forEach(function(e,i){ arr[i]=e.split('-').splice(0,3).join('-') }) console.log(arr) 

You can use String#replace method to remove certain pattern from string using RegExp . 您可以使用String#replace方法使用RegExp从字符串中删除某些模式。

 const input = ["power-still-rate-19.08.22", "main-still-rate-19.08.22", "oil-power-rate-19.08.22","oil-mill-rate-19.7.2"]; const res = input.map(str => str.replace(/-\\d{1,2}\\.\\d{1,2}\\.\\d{1,2}$/, '')); console.log(res); 

You can remove back string by using slice function and join them with join function. 您可以使用slice函数删除后退字符串,然后使用join函数将它们连接起来。

 var arr = ["power-still-rate-19.08.22", "main-still-rate-19.08.22", "oil-power-rate-19.08.22","oil-mill-rate-19.7.2"]; var result = arr.map(str => str.slice(0, str.lastIndexOf('-'))).join(','); console.log(result); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM