skip to Main Content

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


  1. I think your regExp is correct, but need to update replace function.

    function replacer(match, p1, p2, offset, string) {
      if (p2) {
        // If there's a match for the second capturing group (the symbol followed by the rest of the string)
        return '';
      }
      if (p1) {
        // If there's a match for the first capturing group (whitespace)
        return '_';
      }
      return match;
    }
    
    

    Your regExp has two group – (s+), and ([:?.].*$), In updated replacer function parameter p1 for first and parameter p2 for second.

    if p1 is mached, return empty string, and if p2 is mached, return underscore. otherwise return original match string.

    So you can get your expected result.

    Login or Signup to reply.
  2. You can simplify function replacer like this:

    function replacer(text, rem, srch, repl) {
      return text.replace(rem, '').replace(srch, repl);
    }
    
    var str = "Some text .$0 oaisy9";
    
    console.log(replacer(str, /[.?:].*/, / /g, '_'));
    //=> Some_text_

    We have 2 replace invocations in the function:

    1. 1st replace removes text based on regex supplied in argument rem
    2. 2nd replace replaces regex matched by argument srch with repl
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search