Javascript 从变量中删除特定文本 - jquery

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5554869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 17:46:40  来源:igfitidea点击:

remove specific text from variable - jquery

javascript

提问by blasteralfred Ψ

I have a variable in my script containing data test/test1. The part test/is already stored in another variable. I want to remove test/from the previous variable and want to store remaining part in another variable. how can I do this??

我的脚本中有一个包含 data 的变量test/test1。该零件test/已存储在另一个变量中。我想test/从前一个变量中删除并将剩余部分存储在另一个变量中。我怎样才能做到这一点??

Thanks in advance...:)

提前致谢...:)

blasteralfred

布拉拉弗雷德

回答by Zirak

In your case, x/y:

在你的情况下,x/y

var success = myString.split('/')[1]

var success = myString.split('/')[1]

You split the string by /, giving you ['x', 'y']. Then, you only need to target the second element (zero-indexed of course.)

你用 / 分割字符串,给你['x', 'y']. 然后,您只需要定位第二个元素(当然是零索引。)

Edit: For a more general case, "notWantedwanted":

编辑:对于更一般的情况,“notWantedwanted”:

var success = myString.replace(notWantedString, '');

Where notWantedString is equal to what you want to get rid of; in this particular case, "notWanted".

哪里 notWantedString 等于你想要摆脱的;在这种特殊情况下,“不想要”。

回答by Town

If your requirement is as straightforward as it sounds from your description, then this will do it:

如果您的要求与您的描述听起来一样简单,那么可以这样做:

var a = "test/test1";
var result = a.split("/")[1];

If your prefix is always the same (test/) and you want to just strip that, then:

如果您的前缀始终相同 (test/) 并且您只想删除它,那么:

 var result = a.substring(5);

And if your prefix varies but is always terminated with a /, then:

如果您的前缀不同但总是以 / 结尾,则:

var result = a.substring(a.indexOf("/") + 1);

回答by Flash

To split at the first occurence of "/":

在“/”第一次出现时拆分:

var oldstring = "test/test1";
var newstring = oldstring.substring(oldstring.indexOf("/")+1);

There are many other ways to do this, the other answers work fine too.

还有很多其他方法可以做到这一点,其他答案也很好用。

回答by Kon

Have your pick:

随意选择:

JavaScript replace() function.

JavaScript 替换() 函数

var data = "test/test1";
data = data.replace(/data/gi, 'test/');

Or:

或者:

var data = "test/test1";
var dataArray = data.split('/');
var data1 = dataArray[0];
var data2 = dataArray[1];