0

Anybody know, how can i remove signs (&&) with JavaScript on start and on the end of a string?

My string

&& value && value && value &&

or

&& value

or

value &&

I need string like this

value && value && value

or

value
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Juergen
  • 65
  • 7
  • I suggest you read or re-read a basic regexp tutorial. Then you will be able to solve problems like this yourself without having to post here. Any regexp intro will introduce you to the notion of "anchors", which match at the beginning or end of the string. You could start off by [reading this](https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions#Using_special_characters). –  May 31 '17 at 04:56
  • Possible Duplicate of [If text begins or ends with these characters, remove characters](//stackoverflow.com/q/35380077) and [Javascript Remove strings in beginning and end](//stackoverflow.com/q/19134860) – Tushar May 31 '17 at 04:58
  • Do you want to remove only two ampersands, or two or more, or any ampersands including a single one at the beginning and end? –  May 31 '17 at 04:59

3 Answers3

2

With regexp:

// To remove "&" at the beginning and at the end
"&& value && value && value &&".replace(/^&+|&+$/g, '')
   // To remove white spaces
   .trim();
FieryCat
  • 1,875
  • 18
  • 28
0

Use replace to replace the &&

and trim to remove leading/starting white spaces

var string = "&& value && value && value &&";

let replaced = string.replace(/(^&+)|(&+$)/g, "");

console.log(replaced.trim());
A. L
  • 11,695
  • 23
  • 85
  • 163
  • 2
    You don't really need the `(`capturing groups`)`… – deceze May 31 '17 at 04:52
  • @deceze It's just a habit to make things more readable. I do as a precaution mostly. Like how I'll bracket things in an `if` statement even if it isn't needed. – A. L May 31 '17 at 04:54
  • Why not do it all in one go with `/^&+ *| *&+$/`? –  May 31 '17 at 05:04
-1

Try this it will help you,

var s="&& value && value && value &&";
var a=s.match(/[^&/]+/g).join('&&');
alert(a);
user688
  • 361
  • 3
  • 22