0

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.

2
  • 1
    You are removing all special characters, not just &... Commented Mar 26, 2018 at 10:19
  • 1
    It sounds a little like you're trying to encode a value to place it in the querystring, if so try using encodeURIComponent() Commented Mar 26, 2018 at 10:21

4 Answers 4

5

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
Sign up to request clarification or add additional context in comments.

Comments

1

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>

Comments

1

Here you go with one more solution

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

Example

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

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.