Reputation: 3378
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?
Upvotes: 0
Views: 74
Reputation: 56809
/
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);
Upvotes: 2
Reputation: 2378
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 );
}
Upvotes: 0
Reputation:
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...
Upvotes: 1
Reputation: 638
var expression = '/[]+/';
Should be
var expression = '[]+';
Also, adjust the substring indices accordingly http://jsfiddle.net/2Pbm3/4/
Upvotes: 0