Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Search for one or more characters and replace in JavaScript

By using indexOf() I was able to detect if the input contains "SP-" and replace.

However, I need to look for more than one set of characters:
sp-, SP-, eb-, EB- and more…

I have the following to replace sp- and SP- but I don’t want to replicate this entire block for every instance.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

// Check for 'sp-' characters in the order ID.
if (order_id.indexOf("SP-") !== -1) {
  // Remove string from input
  form.find('input[name="orderid"]').val(order_id.replace("SP-", ""));
}

// Check for 'SP-' characters in the order ID.
if (order_id.indexOf("sp-") !== -1) {
  // Remove string from input
  form.find('input[name="orderid"]').val(order_id.replace("sp-", ""));
}

Update – Just thought of a better solution, find all characters before and including - and remove it. So we’re not limited to a specific list in case new prefixes are added at a later date.

sp-1234, SP-1234, xx-1234, etc.

>Solution :

To replace all case insensitive can you try this

form.find('input[name="orderid"]').val(order_id.replace(/sp-/gi, ''));

or you can do something like this

['SP-', 'sp-', 'eb-', 'EB-'].forEach((item)=>{
   if ( order_id.indexOf(item) !== -1 ) {
        // Remove string from input
        form.find('input[name="orderid"]').val(order_id.replace(item, ''));
    }
});

Update – Just thought of a better solution, find all characters before
and including – and remove it. So we’re not limited to a specific list
in case new prefixes are added at a later date.

sp-1234, SP-1234, xx-1234, etc.

Maybe something like this should work

if(order_id.indexOf('-') !== -1) {
 var prefix = order_id.substr(0, order_id.indexOf('-'));
 form.find('input[name="orderid"]').val(order_id.replace(`${prefix}-`, ""));
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading