Arun
Arun

Reputation: 1472

How to replace & and space from a string Angular

I am trying to replace '&' and 'space' from a string.

I can remove the space by string.replace(/[\s]/g, '');

and remove the special character & by string.replace(/[^\da-zA-Z]/g, '')

Can I use both regex in one code? for removing special charecters and space from the string.

Upvotes: 0

Views: 814

Answers (4)

Darshan Vachhani
Darshan Vachhani

Reputation: 549

Try this if you don't want to use regex.

var str = "abc def & ghi jkl & mno";
console.log(str.split(' ').join('').split('&').join(''));

first replace space with null and than replace '&' with null.

It might be help you.

Upvotes: 1

Shiladitya
Shiladitya

Reputation: 12181

Here you go with one more solution

.replace(/ |&/g,'')

Example

var a = "asdasdas dsadasdas dasdas asdas & dasdasd &&&&";
console.log(a.replace(/ |&/g,''));

Upvotes: 1

4b0
4b0

Reputation: 22323

Combine regex for & and space /[& ]+/g

var str='abzx12&  1'
console.log(str.replace(/[& ]+/g,''));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 1

brunnerh
brunnerh

Reputation: 184376

Use | to "or" regexes, e.g.

/(\s|&)/g

Grouping via (...) can be necessary to scope what gets or'd.

In this case, you just have two selectors, so it should work without as well.

/\s|&/g

Upvotes: 5

Related Questions