简体   繁体   English

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

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

I've seen several results for removing characters after a specific character - my question is how would I do that with a string? 我已经看到了在特定字符后删除字符的几个结果 - 我的问题是如何使用字符串执行此操作?

Basically, this applies to any given string of data, but let's take a URL: stackoverflow.com/question 基本上,这适用于任何给定的数据字符串,但我们采用URL: stackoverflow.com/question

With given string, and in JS, I'd like to remove everything after ".com", assign ".com" to a variable, and assign the text before ".com" to a separate variable. 使用给定的字符串,在JS中,我想删除“.com”之后的所有内容,将“.com”分配给变量,并将“.com”之前的文本分配给单独的变量。

So, end result: var x = "stackoverlow" var y = ".com" 所以,最终结果: var x = "stackoverlow" var y = ".com"


What I've done so far: 1) Using a combination of split, substring, etc. I can get it to remove pieces, but not without removing part of the ".com" string. 到目前为止我做了什么:1)使用split,substring等组合我可以删除它们,但不能删除部分“.com”字符串。 I'm pretty sure I can do what I want to do with substring and split, I think I'm just implementing it incorrectly. 我很确定我能用subtring和split做我想做的事情,我想我只是错误地实现了它。 2) I'm using indexOf to find the string ".com" within the full string 2)我正在使用indexOf在完整字符串中找到字符串“.com”

Any tips? 有小费吗? I haven't posted my actual code because it's become so garbled with all the different things I've tried (I can go ahead and do so if necessary). 我没有发布我的实际代码,因为它已经变得如此混乱,我尝试过所有不同的东西(如果有必要,我可以继续这样做)。

Thanks! 谢谢!

Use regular expressions. 使用正则表达式。

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

results in 结果是

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

(Why would you want to assign .com to a variable, though? (为什么要将.com分配给变量?

You should really look into Regular Expressions. 你应该真正研究正则表达式。

Here is some code that can get what you are trying to do: 以下是一些可以获取您要执行的操作的代码:

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".split(/\\b(?=\\.)/) => ["stackoverflow", ".com"] "stackoverflow.com".split(/\\b(?=\\.)/) => ["stackoverflow", ".com"]

Or, 要么,

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

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

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