Given a string, I want to remove all of the string from one of the symbols .
, ?
and :
(so the output string does contain neither the symbol nor what follows it) and I want to replace all blanks with underscores.
I am trying the next code, but it does not work.
// Online Javascript Editor for free
// Write, Edit and Run your Javascript code using JS Online Compiler
var str = "Some text .$0 oaisy9";
function replacer(match, p1, p2, offset, string) {
// p1 is non-digits, p2 digits, and p3 non-alphanumerics
var str2 = string.replace(p2, '')
return str2.replace(p1, '_');
}
console.log(str.replace(new RegExp("(s+)|([:?.].*$)","g"), replacer));
I get Some text Some text
while I would expect Some_text_
.
How should I define replacer
or modify the RegExp
?
Thanks!
2
Answers
I think your regExp is correct, but need to update replace function.
Your regExp has two group – (s+), and ([:?.].*$), In updated
replacer
function parameterp1
for first and parameterp2
for second.if
p1
is mached, return empty string, and ifp2
is mached, return underscore. otherwise return original match string.So you can get your expected result.
You can simplify function
replacer
like this:We have 2
replace
invocations in the function:replace
removes text based on regex supplied in argumentrem
replace
replaces regex matched by argumentsrch
withrepl