如何在javascript中从字符串数组中删除特定字符串之后的所有内容
我有一个字符串数组,我想从中删除语句中如何在javascript中从字符串数组中删除特定字符串之后的所有内容,javascript,arrays,string,split,Javascript,Arrays,String,Split,我有一个字符串数组,我想从中删除语句中with之后的任何内容。 例如,让我们使用一个字符串 var str = ['hey what is with you guys', 'you mean with out', 'hello no with is you'] 新的str2应该返回 ['hey what is', 'you mean' , 'hello no' ] 我已经编写了以下代码,但它没有给出理想的输出。 我的代码: 然而,我想要我的输出 ['hey what is', '
with
之后的任何内容。
例如,让我们使用一个字符串
var str = ['hey what is with you guys',
'you mean with out',
'hello no with is you']
新的str2应该返回
['hey what is',
'you mean' ,
'hello no'
]
我已经编写了以下代码,但它没有给出理想的输出。
我的代码:
然而,我想要我的输出
['hey what is',
'you mean' ,
'hello no'
]
我看不出有任何理由将字符串拆分成数组,然后将它们重新连接成字符串;您可以使用String对象的方法管理所有内容: “现代”ES6+解决方案
函数新闻字符串(arr、str){
返回arr.map(字符串=>{
const index=string.indexOf(str);
返回索引>0?string.substr(0,index).trim():string;
})
}
//试验
常量原始=[
“嘿,你们怎么了?”,
“你的意思是不带出去”,
“你好,不,是你”
];
const modified=newStrings(原始,'with')
console.log('original:',original);
console.log('modified',modified)代码>这是一个解决方案建议,使用ES6功能,如
const str=[
“嘿,你们怎么了?”,
“你的意思是不带出去”,
“你好,不,我是你”,
];
函数removeWith(arr){
//从输入数组创建数组
返回arr.map((行)=>{
//对于每一行,用单词“with”拆分字符串
//我使用带有'sensitive'标志的正则表达式使其不区分大小写。
//所以它与“with”和“with”和“with”一起工作。。。
返回行。拆分(/with/i)[0];
//[0]将返回字符串的第一部分,即使未拆分任何内容。
});
}
你可以试试这个,效果很好
var str=['嘿,你们怎么了',
“你的意思是不带出去”,
“你好,不,我是你”]
设arr2=[]
函数newArray(str){
对于(var i=0;i),您似乎不仅要删除“with”之后的所有内容,还要删除“with”一词及其前面的任何空格。您描述的“output is”是循环中的控制台。log
一个接一个,实际上不是一个连续数组。您可以尝试.map(s=>s.match(/^(.*)(\s*with |$)/)[1])
。通过删除var-arr2=[]
,将以下行更改为newArr=newArr.concat(j[0].trimEnd());
,然后放置var-newArr=[]
在循环之前。@ASDFGerte是的,它成功了。非常感谢。小附录:上面的修复仍然有一个小问题。即使字符串中没有“with”,它也会在末尾修剪空白。例如,输入['nothing to find here but spaces']
将返回['nothing to find here but spaces']
。您必须检查split
是否实际拆分,才能涵盖这一点。
[ 'hey what is ' ]
[ 'you mean ' ]
[ 'hello no ' ]
['hey what is',
'you mean' ,
'hello no'
]