user1265083
user1265083

Reputation: 107

javascript regex replace nonwords and spaces does not work?

var st = "Dream Theater A Change of Seasons (EP) (1995)";
var searchTerm = st.replace("/[\s\W]+/g", "+");

gives Dream Theater A Change of Seasons EP 1995

but I want to be
Dream+Theater+A+Change+of+Seasons+EP+1995+

Upvotes: 0

Views: 435

Answers (3)

Phil
Phil

Reputation: 2307

var searchTerm = st.replace(/[\s\W]+/g, '+');

Upvotes: 0

Vadim Baryshev
Vadim Baryshev

Reputation: 26179

You need:

var searchTerm = st.replace(/[\s\W]+/g, "+");

without quotes.

Upvotes: 2

hvgotcodes
hvgotcodes

Reputation: 120168

try

st.replace(/\s/g, "+");

which just replaces every whitespace char with a +. Also note I removed the quotes around the regex -- you want a regex, not a string.

EDIT -- Just tried

st.replace(/[\s\W]+/g, "+"); // no quotes around the regex

and that gives you the + on the end. So the real problem is you are passing a string when you want to pass an actual regex reference.

Upvotes: 1

Related Questions