[英]Trim a string from end or start
I have a String in JavaScript. 我在JavaScript中有一个String。 Say
var val = %Hello;
说
var val = %Hello;
or sometimes var val = Hello%;
或有时
var val = Hello%;
I need to trim '%' from the String to get Hello
. 我需要从字符串中修剪'%'以获得
Hello
。 How to do this in javascript? 如何在javascript中做到这一点?
Simply replace the %
character with a blank string. 只需将
%
字符替换为空白字符串即可。
var val = "%Hello";
val = val.replace('%', '');
alert(val); //alerts "Hello"
var val = "Hello%";
val = val.replace('%', '');
alert(val); //alerts "Hello"
var val = "%Hello%";
val = val.replace('%', '');
If I got you well, 如果我一切都好
var val = "%Hello"
var reg= new RegExp ("%");
val = val.replace (reg, "");
should work. 应该管用。 (I call regexp to show you the good way if you show up with more complicate examples).
(如果您出现更多复杂的示例,则我称regexp为您展示一种好方法)。 But
但
var val = "%Hello";
val = val.replace ("%", "");
will be faster. 会更快。
val = 'Whatever%'; //or %Whatever
val.replace('%', '');
var finalstring = val.replace(/^\s+|\s+$/g,''); //trimming
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.