JavaScript - Regex, is there a marker for any string?
Solution 1
The dot (.
) matches any (1) character; .+
matches a string of at least length 1, .*
matches a string of at least length 0.
Solution 2
A period is used to represent any character that is not a line break, but to represent any character you can use a set with two complementing sets, like all alphanumeric characters and all non-alphanumeric characters:
str = str.replace(/\w*([\W\w])/g, "($1)");
That will match a single character, if you want to match more than one you have to specify how many. [\W\w]{1,3}
would for example match one to three characters. [\W\w]+
would match everything to the end of the string.
Note that you don't need a callback for a simple replacement like this, just a string where $1
is substituted with the first caught value.
Edit:
Come to think of it, as the character is following a set that matches alphanumeric characters, it has to be non-alphanumeric, so just \W
will do:
str = str.replace(/\w*(\W)/g, "($1)");
Comments
-
Freezy Ize almost 2 years
str.replace(/\w*(\ || --> A marker whitch can represent any char or string? <-- || )/g, function() {return "(" + arguments[0] + ")"})
-
Guffa about 11 years@FreezyIze: When I try it, I get exactly the expected output. Demo: jsfiddle.net/EaJSq/1
-
Freezy Ize about 11 yearsGood answer, but it doesn't search for "any string".
-
Freezy Ize about 11 yearsPlease try out the answer above
-
Guffa about 11 years@FreezyIze: That does the same, except it doesn't work for all characters. I already covered that in the first sentence of my answer.