删除某个角色后的所有内容

Dej*_*n.S 252 javascript jquery

有没有办法删除某个角色后的所有内容,或者只选择该角色的所有内容?我从href获得了值,直到"?",它总是会有不同数量的字符.

像这样

/Controller/Action?id=11112&value=4444
Run Code Online (Sandbox Code Playgroud)

我希望href /Controller/Action只是,所以我想删除"?"之后的所有内容.

我现在正在使用它:

 $('.Delete').click(function (e) {
     e.preventDefault();

     var id = $(this).parents('tr:first').attr('id');                
     var url = $(this).attr('href');

     console.log(url);
 }
Run Code Online (Sandbox Code Playgroud)

Dem*_*cht 426

var s = '/Controller/Action?id=11112&value=4444';
s = s.substring(0, s.indexOf('?'));
document.write(s);
Run Code Online (Sandbox Code Playgroud)

这里有样品

编辑:

我还要提一下,本机字符串函数比正则表达式快得多,正则表达式应该只在必要时使用(这不是其中一种情况).

第二编辑:

更新了代码以解释没有'?':

var s = '/Controller/Action';
var n = s.indexOf('?');
s = s.substring(0, n != -1 ? n : s.length);
document.write(s);
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/L4hna/1/

  • 这意大利面条代码不应该是最好的答案.看到拆分方法的答案 (6认同)
  • 如果角色不存在,它将什么也不显示 (4认同)
  • LoL - 不知何故,那些不理解正则表达式以及 split 工作原理的人获得了投票权。了解 String 方法就足够了。最不了解事物是如何工作的,最大的代码统治着世界:P所以我在分割答案中添加了一步一步的解释(以改变世界)。 (2认同)

kap*_*apa 254

您也可以使用该split()功能.这似乎是我脑海中最简单的:).

url.split('?')[0]
Run Code Online (Sandbox Code Playgroud)

jsFiddle演示

一个优点是即使?字符串中没有,此方法也会起作用- 它将返回整个字符串.

  • +1,最好的事情就是它总是有效,即使没有'?' (38认同)
  • `split`返回一个数组(在这种情况下它有两个元素,`0`和`1`),`[0]`获取返回数组的第一个元素. (12认同)
  • 喜欢这个答案,如此简单,但它为您提供的功能却非常强大 (2认同)
  • 实际上我改变了这个答案,因为它更灵活,而且总体上是一个更干净的解决方案。 (2认同)
  • 您可以通过将 limit 参数添加到 split 函数来稍微优化答案:`url.split('?', 1)[0]` (2认同)

Jam*_*urz 18

var href = "/Controller/Action?id=11112&value=4444";
href = href.replace(/\?.*/,'');
href ; //# => /Controller/Action
Run Code Online (Sandbox Code Playgroud)

如果找到'?',这将有效 如果没有

  • 这将删除`?`(包括)之后的所有内容 (3认同)
  • **最佳答案**!OP 要求删除 `?` 之后的所有内容,并明确说明要删除 `?` 还说:***我希望 href 仅为 /Controller/Action *** (2认同)

Cod*_*iac 12

聚会可能会很晚:p

您可以使用反向引用$'

$' - Inserts the portion of the string that follows the matched substring.
Run Code Online (Sandbox Code Playgroud)

$' - Inserts the portion of the string that follows the matched substring.
Run Code Online (Sandbox Code Playgroud)


小智 7

您还可以使用split()对我来说是实现此目标的最简单方法的方法。

例如:

let dummyString ="Hello Javascript: This is dummy string"
dummyString = dummyString.split(':')[0]
console.log(dummyString)
// Returns "Hello Javascript"
Run Code Online (Sandbox Code Playgroud)
来源:https://thispointer.com/javascript-remove-everything-after-a-certain-character/


小智 6

它非常适合我:

var x = '/Controller/Action?id=11112&value=4444';
var remove_after= x.indexOf('?');
var result =  x.substring(0, remove_after);
alert(result);
Run Code Online (Sandbox Code Playgroud)


pat*_*tad 5

如果您还想保留“?” 然后删除该特定字符之后的所有内容,您可以执行以下操作:

var str = "/Controller/Action?id=11112&value=4444",
    stripped = str.substring(0, str.indexOf('?') + '?'.length);

// output: /Controller/Action?
Run Code Online (Sandbox Code Playgroud)