1

I have a string of the following format:

"hello(%npm%)hi"

My goal is to split the string into three parts

a) hello
b) (%npm%)
c) hi

I am using regex as follows:

var myString = "hello(%npm%)hi".match(/[a-z]*/);
        var backdtring  = "hello(%npm%)hi".match(/\)[a-z]*/);
        var midstring  = "hello(%npm%)hi".match(/\(\%[a-z]*\%\)/);

var res = backdtring.replace(")", "");

https://jsfiddle.net/1988/ff6aupmL/

I am trying in jsfiddle , where theres an error in the line:

var res = backdtring.replace(")", "");

"backdtring.replace is not a function" .

Whats wrong in the replace function above?

Update: Also, have I used the best practices of regular expressions ?

3
  • 4
    .match of regex returns an array of matches. .replace() cannot be applied to arrays. console.log(backdtring) would have revealed that. Commented Jan 6, 2017 at 11:43
  • 1
    jsfiddle.net/satpalsingh/uj6rqjhf Commented Jan 6, 2017 at 11:44
  • 2
    str.match(/\w+/g) Commented Jan 6, 2017 at 11:44

1 Answer 1

2

As it has been mentioned in the comments, you are trying to use a String#replace method on an array, see the description of the return value of String#match:

An Array containing the entire match result and any parentheses-captured matched results; null if there were no matches.

To streamline tokenization, I'd rather use .split(/(\([^()]*\))/) to get all substrings in parentheses and the substrings that remain:

var s = "hello(%npm%)hi";
var res = s.split(/(\([^()]*\))/);
console.log(res);

Details:

  • (\([^()]*\)) - the pattern is enclosed with capturing group so as split could return both the substrings that match and those that do not match the pattern
  • \( -a literal (
  • [^()]* - 0+ chars other than ( and )
  • \) - a literal ).

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.