Einarr
Einarr

Reputation: 332

Add parameter to String#replace

I want to remove the last character from a string if it is a pipe. I have

.replace(/\|(\s+)?$/, '')

I want to add a parameter delim to replace since the last character changes. I am trying:

.replace(/\+delim +(\s+)?$/, '')

but no luck.

The code that uses this function:

 rangeValues[cellRow][hn[j]] = rangeValues[cellRow][hn[j]].toString()
     .split(frValues[i][0])
     .join(frValues[i][1]).trim()
     .replace(/\ + delim + (\s+)?$/, '');

Upvotes: 1

Views: 87

Answers (1)

Tanaike
Tanaike

Reputation: 201388

  • You want to remove a last character using regex.
  • You want to use by changing delim in the regex.

If my understanding for your question is correct, how about using RegExp?

Modified script:

var delim = "|";
var string = "\\" + delim + "(\\s+)?$";
var regex = new RegExp(string);

rangeValues[cellRow][hn[j]] = rangeValues[cellRow][hn[j]].toString()
     .split(frValues[i][0])
     .join(frValues[i][1]).trim()
     .replace(regex, '');

Note :

  • When delim is |, regex becomes /\|(\s+)?$/.

Reference:

If I misunderstand your question, I'm sorry.

Upvotes: 1

Related Questions