JS-删除字符串之前/之后的所有字符(并保留该字符串)

JS - Remove all characters before/after a string (and keep that string)?

本文关键字:字符串 字符 保留 删除 JS- 之后      更新时间:2023-09-26

我看到了删除特定字符后的字符的几个结果——我的问题是如何使用字符串?

基本上,这适用于任何给定的数据字符串,但让我们取一个URL:stackoverflow.com/question

对于给定的字符串,在JS中,我想删除".com"之后的所有内容,将".com"分配给一个变量,将"com"之前的文本分配给另一个变量。

因此,最终结果:var x = "stackoverlow" var y = ".com"


到目前为止我所做的:1( 使用split、substring等的组合,我可以让它删除片段,但不能不删除".com"字符串的一部分。我很确定我可以用子字符串和split做我想做的事情,我认为我只是实现错误了。2( 我正在使用indexOf在完整字符串中查找字符串".com">

有什么建议吗?我还没有发布我的实际代码,因为它被我尝试过的所有不同的东西弄得一团糟(如果必要的话,我可以继续做(。

谢谢!

您真的应该研究正则表达式。

这里有一些代码可以得到你想要做的事情:

var s = 'stackoverflow.com/question';
var re = /(.+)('.com)(.+)/;
var result = s.match(re); 
if (result && result.length >= 3) {
    var x = result[1], //"stackoverlow"
        y = result[2]; //".com"
    console.log('x: ' + x);
    console.log('y: ' + y);
}

使用正则表达式。

"stackoverflow.com".match(/(.+)('.com)/)

中的结果

["stackoverflow.com", "stackoverflow", ".com"]

(为什么要将.com分配给一个变量?

"stackoverflow.com".split(/'b(?='.)/)=>["stackoverflow", ".com"]

或者,

"stackoverflow.com/question".split(/'b(?='.)|(?='/)/)
=>["stackoverflow", ".com", "/question"]