0
var str = "in this sentence, I WANT TO GET ONLY THIS PART - not the other parts"

Assume I want to get the part which is starts with , and ends with -

I always use split in order to cut or get the sub-sentence. Because I don't know how to write a regex.

For this example I wrote as;

str.split(",")[1].split("-")[0]
" I WANT TO GET ONLY THIS PART "

Is it efficient to use split? Or how can I write a regex which will take the same part. Which one should I choose? regex or split? What do you suggest and why?

edit: Thank you for giving me the exact regex, but I also want to know which way is better? Using split is also a solution? Or should I learn how to write a regex?

4
  • Hi, First of all you need to answer a few qestions : 1) Will your string remain the same? 2) You always have to separate the string that is AllCaps? Commented Mar 3, 2017 at 6:35
  • Actually allCaps is just for emphasizing the string that I want to cut. There is no need for it. I just want to get string between "," and "-" for example. Commented Mar 3, 2017 at 6:37
  • 1
    You could use .split() with a regex: str.split(/[,-]/)[1]. Or str.split(/(?:, *)|(?: *-)/)[1] to avoid the leading and trailing spaces. (I'm not saying you should, but you could...) Commented Mar 3, 2017 at 6:42
  • @nnnnnn thank you! I have never see using split with regex, this is good. Commented Mar 3, 2017 at 6:46

1 Answer 1

3

You can use the following regex :

,\s?(.*?)\s?-

JavaScript

var str = "in this sentence, I WANT TO GET ONLY THIS PART - not the other parts";
var result = str.match(/,\s?(.*?)\s?-/);
console.log(result[1]);

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

2 Comments

result will be <space>RESULT<space>
+1 for the fix.. yet, this will fail when the result needed contains , or - maybe get first index of , then last index of -? :D

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.