0

I must have a syntax error in my code but I can't see it. fiddle here

var comma = ',,';
var stop = '.。';
var expression = '/[]+/';

expression = expression.substr(0,2) + comma + stop + expression.substr(2);
expression = new RegExp(expression,'g');

var res = "foo,吧。baz".split(expression);

for ( var n=0; n < res.length; n++ ) {
}

I'm expecting res.length to be 3 but it is always 1 and returns the full string. What am I missing?

1
  • 1
    The problem is that you don't need / if you use RegExp constructor. Commented Sep 20, 2013 at 5:19

4 Answers 4

1

When you creat your Regex you're using this: var expression = '/[]+/';. The / delimiters are for use when you're delaring a regex like this:

var expression = /[]+/;   // note: no quotes.

You're using new Regexp(), so they're not required in your string. Removing them gives this:

var comma = ',,';
var stop = '.。';
var expression = '[]+';

expression = expression.substr(0,1) + comma + stop + expression.substr(1);
expression = new RegExp(expression,'g');

var res = "foo,吧。baz".split(expression);

for ( var n=0; n < res.length; n++ ) {
  var item = document.createElement('li');
  item.innerHTML = res[n];
  document.getElementById('list').appendChild( item );
}

Which does what you expect. See this fiddle. I've adjusted the string indices and the loop index so that things work...

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

Comments

1

/ is used as delimiter for RegExp literal. e.g. /[a-zA-Z]/g

/ is not needed when you pass a pattern to the RegExp constructor. e.g. new RegExp('[a-zA-Z]', 'g')

To resolve the problem, remove the / (and modify the rest of your code):

var expression = '[]+';

Or you can just pass a RegExp literal directly:

var res = "foo,吧。baz".split(/[,,.。]+/g);

Comments

0
var expression = '/[]+/';

Should be

var expression = '[]+';

Also, adjust the substring indices accordingly http://jsfiddle.net/2Pbm3/4/

Comments

0

Working like this :

var comma = ',,';
var stop = '.。';
var expression = '[]+';

expression = expression.substr(0,1) + comma + stop + expression.substr(1);
expression = new RegExp(expression,'g');

var res = "foo,吧。baz".split(expression);

for ( var n=0; n < res.length; n++ ) {
    var item = document.createElement('li');
    item.innerHTML = res[n];
    document.getElementById('list').appendChild( item );
}

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.