1

I've a text variable in the following format -

value1|34|value2|45|value3|67|value4|687|

Now I just have the text 'value3' with me and I've to remove that value along with its associated number from the above string. After removing it I've to get -

value1|34|value2|45|value4|687|

Note: The numbers in the pipelines are prefixed with its value string. Ex - Value|56|. So if I've to remove a value I've to remove it along with its number.

Mathias Bynens
  • 144,855
  • 52
  • 216
  • 248
NLV
  • 21,141
  • 40
  • 118
  • 183

3 Answers3

2

It looks like you could benefit from using something like JSON as a storage format instead.

'value1|34|value2|45|value3|67|value4|687|'.replace(/value3\|\d+\|/,'')
Wivlaro
  • 1,455
  • 1
  • 12
  • 18
1
var input = 'value1|34|value2|45|value3|67|value4|687|',
    remove = 'value3',
    result = input.replace(RegExp(remove + '\\|\\d+\\|'), '');
console.log(result); // 'value1|34|value2|45|value4|687|'
Mathias Bynens
  • 144,855
  • 52
  • 216
  • 248
  • Not working :(. I'm still getting the same original string after replacing it. – NLV Jun 21 '12 at 13:12
  • If the value has some special character like this - "Test: (Has- Characters)" it is not working. I'm not able to figure out which of the character is causing the issue. – NLV Jun 21 '12 at 13:59
  • I guess parentheses () is causing the issue. How to fix it? – NLV Jun 21 '12 at 14:03
  • Replace `\d` (which only matches digits) with a character class that would match everything you want to match, e.g. `[0-9a-zA-Z\(\)\s-]`, or simply use `[^|]`. – Mathias Bynens Jun 21 '12 at 16:35
1

You can

var s = "value1|34|value2|45|value3|0000|value4|687|";
var r = "value3";

s = s.replace(new RegExp("(?:^|\\|)" + r + "\\|\\d+"), "")

Includes start-guard (wont match xxxvalue3)

Alex K.
  • 171,639
  • 30
  • 264
  • 288
  • This is removing the pipeline before the value. For example, after you remove value3 I'm getting - value1|34|value2|45value4|687| – NLV Jun 21 '12 at 13:34
  • If the value has some special character like this - "Test: (Has- Characters)" it is not working. I'm not able to figure out which of the character is causing the issue. – NLV Jun 21 '12 at 14:00
  • I guess parentheses () is causing the issue. How to fix it? – NLV Jun 21 '12 at 14:03
  • Changed re; to use a string that contain characters that form part of re syntax you must escape it; http://stackoverflow.com/questions/3446170/escape-string-for-use-in-javascript-regex – Alex K. Jun 21 '12 at 14:28