tam tam
tam tam

Reputation: 1900

how to use javascript regex to remove characters from string

I have a string value which would look like the following with sample

data:


130823  ~ Optics-Bottle Detect failure ~ L 0 ~ P 0 | 130824 ~ Optics-Bubble Detect failure ~ L 0 ~ P 0

Format:

ID:          130823
Description: Optics-Bottle Detect failure 
Reps:        L O
Pending:     P 0

My final string should basically remove the ID from each part in the concatenated string so by looking at the above sample data the desired output should be as follows:

 Optics-Bottle Detect failure ~ L 0 ~ P 0 | Optics-Bubble Detect failure ~ L 0 ~ P 0 

There could be N number of parts in one string. For the sake of example I only included a sample string which has two parts in it.

**My Regex

Im using the following regular expression but it only removed the ID from the first part in the string

var y = x.replace(/\d{6}\s~\s/g, "");

Upvotes: 5

Views: 10343

Answers (2)

gilly3
gilly3

Reputation: 91467

Split the string into a multidimensional array using the delimiters " | " and " ~ ". Then you can .shift() off the id, since it is the first entry in the array, and join it all back together:

var y = x.split(" | ").map(function(s) {
    s = s.split(" ~ ");
    s.shift();
    return s.join(" ~ ");
}).join(" | ");

Or, get the substring after the " ~ ":

var y = x.split(" | ").map(function(s) {
    return s.substr(s.indexOf(" ~ ") + 3);
}).join(" | ");

Or, correct your RegExp to account for whitespace length variation:

var y = x.replace(/\d{6}\s+~\s/g, "");

But, this RegExp will only work as long as there are always exactly 6 digits in the id, and never 6 digits preceding a ~ elsewhere. For example, if there should ever be a value for Reps of 100000 or more, your RegExp will remove that as well.

A better regular expression would take any number of digits (more or less than 6) and would only match it if it's the first item, or follows a |:

var y = x.replace(/(^|\|\s+)\d+\s+~\s+/g, "$1");

Upvotes: 1

epsilones
epsilones

Reputation: 11609

Here's a possible answer, for example

var str = "144515 ~ Commodities-Damaged Reagent Cartridge ~ L 0 ~ P 0 | 144516 ~ Commodities";
var n=/\d{6}\s+~/g;
str = str.replace(n, "");

Upvotes: 4

Related Questions