Nidheesh
Nidheesh

Reputation: 4562

Trim a string from end or start

I have a String in JavaScript. Say var val = %Hello; or sometimes var val = Hello%; I need to trim '%' from the String to get Hello. How to do this in javascript?

Upvotes: 0

Views: 90

Answers (4)

coolguy
coolguy

Reputation: 7954

val = 'Whatever%'; //or %Whatever
val.replace('%', '');
var finalstring = val.replace(/^\s+|\s+$/g,''); //trimming

Upvotes: 1

Jerska
Jerska

Reputation: 12002

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). But

var val = "%Hello";
val = val.replace ("%", "");

will be faster.

Upvotes: 1

Curtis
Curtis

Reputation: 103358

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"

Upvotes: 3

yogi
yogi

Reputation: 19591

var val = "%Hello%";
val = val.replace('%', '');

Upvotes: 1

Related Questions