javascript 使用Javascript删除$符号后的所有字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6102910/
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
Remove all the characters after $ sign using Javascript
提问by Janet
I want to remove all the characters that appear after "$" sign in my string using javascript.
我想使用javascript删除字符串中“$”符号后出现的所有字符。
Is there any function in javascript which can help me achieve this. I am quite new to client side scripting.
javascript中是否有任何功能可以帮助我实现这一目标。我对客户端脚本很陌生。
Thanks.
谢谢。
采纳答案by Jonathon
there are a few different ways
有几种不同的方式
var myStr = "asdasrasdasd$hdghdfgsdfgf";
myStr = myStr.split("$")[0];
Or
或者
var myStr = "asdasrasdasd$hdghdfgsdfgf";
myStr = myStr.substring(0, myStr.indexOf("$") - 1);
回答by Hogan
How about this
这个怎么样
astr.split("$")[0];
NB This will get you all of the characters up to the $
. If you want that character too you will have to append it to this result.
注意这将使您获得所有字符直到$
. 如果您也想要该字符,则必须将其附加到此结果中。
回答by Rocket Hazmat
You can try this regex, it will replace the first occurance of $
and everything after it with a $
.
你可以试试这个正则表达式,它将取代中第一次出现$
了,一切之后$
。
str.replace(/$.*/, '$');
Input: I have $100
Output: I have $
输入:I have $100
输出:I have $
回答by Dustin Laine
You need to get the substring and pass the index of the $
as it's second parameter.
您需要获取子字符串并传递$
它的索引作为第二个参数。
var newString = oldString.substring(0, oldString.indexOf("$", 0))
回答by Craig M
Use the subtring and indexOf methods like so:
像这样使用 subtring 和 indexOf 方法:
var someString = "12345890";
alert(someString.substring(0, someString.indexOf('$')));
回答by Thomas Shields
Use .split()
to break it up at the dollar signs and then grab the first chunk:
用于.split()
在美元符号处将其分解,然后获取第一个块:
var oldstring = "my epic string $ more stuff";
var split = oldstring.split("$");
var newstring = split[0] + "$";
alert(newstring); //outputs "my epic string $"
回答by pimvdb
Regular expressions are very helpful:
正则表达式非常有用:
/([^$]*$?)/.exec("aa$bc")[1] === "aa$"