0

How can I separate my string by regex match()? I want use only jQuery RegEx.

var MyStr = 'BeginStr ABCDEF EndStr' // The result should: ABCDEF 

How can I separate "ABCDEF"?

Below is a solution, but I like to improve it, how can I eliminate the function replace()? I want use only one time the function match().

var MyStr = 'BeginStr ABCDEF EndStr';  // The result should:  ABCDEF
sRegEx = /BeginStr.*?(?=EndStr)/;
var sResult = String(MyStr.match(sRegEx)); // It results: BeginStr ABCDEF
var sMenuPoint = String(MyStr.match(sRegEx)).replace(/BeginStr/, ''); // It results: ABCDEF
alert(sResult);

Thanks in advance, Sandro.

3
  • 4
    The code example doesn't use jQuery, just plain JavaScript. Commented Mar 13, 2014 at 22:43
  • Sorry. I correct my string: The string to cut is between "BeginStr" and "EndStr". var MyStr = 'any string BeginStr ABCDEF EndStr other string'; Commented Mar 13, 2014 at 22:54
  • Thank you, it works :) But I still would like to know whether it would be feasible with match ()? Here is the corrected string: var MyStr = 'any string BeginStr ABCDEF EndStr other string'; Commented Mar 13, 2014 at 23:20

1 Answer 1

2

Using simple replace() function will do it for you along with group capturing($1, $2, etc):

sResult = MyStr.replace(/.*BeginStr(.*?)(?=EndStr).*/, "$1");

or

sResult = MyStr.replace(/.*BeginStr(.*?)EndStr.*/, "$1");
Sign up to request clarification or add additional context in comments.

3 Comments

Although I agree with your solution, OP asked 'how can I eliminate the function replace()?'
@aduch I thought by 'imporove it' he meant to use only one function, can be either replace or match. May be I was confused!!
Maybe I'm the one confused anyways +1.

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.