2

I am new to JavaScript. I have a variable:

var externalClientDataBody = {"hotelCodes":"CUNMXSAKU_3d,CUNMXMAYA_4d"};

I want to split it on delimeter "_". I want my output to look like this:

var externalClientDataBody = {"hotelCodes":"CUNMXSAKU,CUNMXMAYA"};

I can ignore "_3d _4d" and want to get my string comma separated like "CUNMXSAKU,CUNMXMAYA". Is there any way to do this using RegExp?

4
  • Are there always just two things in the list, or could it be more? Commented Oct 2, 2015 at 14:55
  • 1
    You've said "split," but you're not doing any splitting in the above, you're just removing _3d and _4d from the one string. Commented Oct 2, 2015 at 14:56
  • @Anders Could me more Commented Oct 2, 2015 at 14:58
  • You can also use 'CUNMXSAKU_3d'.match(/([^_]+)/)[1] to extract all the characters before _. Commented Oct 2, 2015 at 18:48

2 Answers 2

4

If your goal is to remove the _ and anything following it through the end of the word, you can do it by matching _ followed by "word" characters (\w) and replacing with "":

str = str.replace(/_\w+/g, '');

Live Example:

var externalClientDataBody = {"hotelCodes":"CUNMXSAKU_3d,CUNMXMAYA_4d"};
externalClientDataBody.hotelCodes = externalClientDataBody.hotelCodes.replace(/_\w+/g, '');
snippet.log(externalClientDataBody.hotelCodes);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

0

This should do the trick:

var regex = new RegExp('(^[^_]+)')
var input = 'dasddffsdff_d3';
var result = regex.exec(input);
//result = 'dasddffsdff'

RegExr link

3 Comments

Result will not be as shown with the above. It will be an array with two entries, ["dasddffsdff", "dasddffsdff"].
@T.J.Crowder I thought you would use it in a loop.
If you're going to say "result =" it should be correct. Moreover, .exec is the wrong tool for this job.

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.