0

I have a string with sub-string '5+' and it looks like sales/100/5+. I need to remove the sub-string 5+.

Input : sales/100/5+

Demanded output : sales/100

The jquery script is as follows:

var rstring = 'sales/100/5+';
if((splitStr == '5+')||(splitStr == '4-')) {
    var key = rstring.replace(new RegExp('/'+splitStr, 'g'),"");
    alert(key);
}

Now im getting the result : sales/100+

But desired output is : sales/100

1
  • Is the part to be replace always "5+" / "4-" or is it gonna be the part after last "/" ?? Commented Apr 26, 2017 at 9:04

3 Answers 3

1

To achieve this you can split() the string by /, remove the last element, then join() it back together, like this:

var arr = 'sales/100/5+'.split('/');
arr.pop();

console.log(arr.join('/'));

Sign up to request clarification or add additional context in comments.

Comments

1

You don't really need to use a Regex to make your string replace work

the simplest the best :

  var rstring = 'sales/100/5+';
  if((splitStr == '5+')||(splitStr == '4-')) 
  {
       var key = rstring.replace('/' + splitStr, '');
       alert(key);
  }

the '+' in your Regex is a quantifier. It matches between one and unlimited times, as many times as possible, giving back as needed. That's why your + was still ther after your replace.

Comments

0

You can remove /5+ from given strings. No jQuery code is neede, just a simple JS function.

function replace5plus(str) {
    return str.replace('/5+', '');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.