繁体   English   中英

删除某个字符后的所有内容

[英]Remove everything after a certain character

有没有办法在某个角色之后删除所有内容,或者只选择该角色之前的所有内容? 我从一个href到“?”的值,它总是会有不同数量的字符。

像这样

/Controller/Action?id=11112&value=4444

我希望 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);
 }
var s = '/Controller/Action?id=11112&value=4444';
s = s.substring(0, s.indexOf('?'));
document.write(s);

样品在这里

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

更新代码以考虑没有“?”:

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

样品在这里

您还可以使用split()函数。 这似乎是我想到的最简单的一个:)。

url.split('?')[0]

jsFiddle 演示

一个优点是这种方法即使没有? 在字符串中 - 它将返回整个字符串。

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

如果找到“?”,这将起作用如果没有

它非常适合我:

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

可能是很晚的派对:p

您可以使用反向引用$'

$' - Inserts the portion of the string that follows the matched substring.

 let str = "/Controller/Action?id=11112&value=4444" let output = str.replace(/\\?.+/g,"$'") console.log(output)

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

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

// output: /Controller/Action?

如果你添加一些 json syringified 对象,那么你也需要修剪空间......所以我也添加了 trim()。

let x = "/Controller/Action?id=11112&value=4444";
let result =  x.trim().substring(0,  x.trim().indexOf('?'));  

为我工作:

      var first = regexLabelOut.replace(/,.*/g, "");

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

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

它可以很容易地使用 JavaScript 完成以供参考,请参阅链接JS String

编辑它可以很容易地完成。 ;)

var url="/Controller/Action?id=11112&value=4444 ";
var parameter_Start_index=url.indexOf('?');
var action_URL = url.substring(0, parameter_Start_index);
alert('action_URL : '+action_URL);

暂无
暂无

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

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