2

I'm trying to generate a link using jQuery and need to trim the last '+' sign off the end. Is there a way to detect if there is one there, and then trim it off?

So far the code removes the word 'hotel' and replaces spaces with '+', I think I just need another replace for the '+' that shows up sometimes but not sure how to be super specific with it.

var nameSearch = name.replace("Hotel", "");
nameSearch = nameSearch.replace(/ /g, "+");
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Nomi
  • 23
  • 3
  • 1
    I answered the title. But what is the usecase. Why do you have spaces that you need to get rid of and why do they appear? Can you explain the actual situation? What is the content of `name` and what should the link look like – mplungjan Mar 30 '21 at 08:34

3 Answers3

6

The answer to

What is the regex to remove last + sign from a string

is this

const str = "Hotel+"
const re = /\+$/; // remove the last plus if present. $ is "end of string"
console.log(str.replace(re,""))

The question is however if this is answering the actual problem at hand

If you have the string

"Ritz Hotel"

and you want to have

https://www.ritz.com

then you could trim the string:

const fullName = "Ritz Hotel",
  name = fullName.replace("Hotel", "").trim().toLowerCase(),
  link = `https://www.${name}.com`;

console.log(link)

// or if you want spaces to be converted in url safe format

const fullName1 = "The Ritz Hotel",
  name1 = fullName1.replace("Hotel", "").trim().toLowerCase(),
  link1 = new URL(`https://www.hotels.com/search?${name1}`).toString()

console.log(link1)
mplungjan
  • 169,008
  • 28
  • 173
  • 236
3

As an alternative to mplungjan's answer, you can use str.endsWith() for the check. If it ends on the + it will be cut out. There is no need for regex. If you can avoid regex you definitely should.

let str = "Hotel+";
if (str.endsWith("+")) {
  str = str.substr(0, str.length - 1);
}
console.log(str);

Below you can find a function to replace all the whitespace characters with + excluding the last one:

const raw = "My Ho te l ";

function replaceSpacesWithPlus(raw) {
  let rawArray = Array.from(raw);
  let replArray = [];
  for (let i = 0; i < rawArray.length; i++) {
    const char = rawArray[i];
    // handle characters 0 to n-1
    if (i < rawArray.length - 1) {
      if (char === ' ') {
        replArray.push('+');
      } else {
        replArray.push(char);
      }
    } else {
      // handle last char
      if (char !== ' ' && char !== '+') {
        replArray.push(char);
      }
    }
  }
  return replArray;
}

console.log(replaceSpacesWithPlus(raw));
F. Müller
  • 3,969
  • 8
  • 38
  • 49
  • 1
    Why avoid regex? My example detects AND removes in one statement – mplungjan Mar 30 '21 at 08:04
  • https://stackoverflow.com/questions/998997/should-i-avoid-regular-expressions – mplungjan Mar 30 '21 at 08:12
  • @mplungjan Because regex is slow and the syntax is hard to extend if you want to implement new features. If you can use built-in functions like `endsWith` it will do a much faster lookup than regex. – F. Müller Mar 30 '21 at 08:25
  • I can imagine if you need to process 10s of thousands of lines. In this case, I will defend my code is the most pragmatic solution to this specific issue. – mplungjan Mar 30 '21 at 08:26
  • I completely fail to see the usecase for the large amount of code in your second example – mplungjan Mar 30 '21 at 08:27
  • @mplungjan Disputable. The number of lines of code is not a quality assurance at all. I said it is an alternative. I never said your solution is bad. But if you have to call two regex or character replacement operations that do the same thing over again (iterate over the same characters multiple times) why would you do that. – F. Müller Mar 30 '21 at 08:30
  • But I am not doing that, so the question is moot. – mplungjan Mar 30 '21 at 08:31
  • @mplungjan But he does the whitespace to + character replacement on top of your code. You did not consider this in your code. – F. Müller Mar 30 '21 at 08:32
  • true. I am answering `What is the regex to remove last + sign from a string` without considering the X/Y problem in the question. I apologise – mplungjan Mar 30 '21 at 08:33
  • @mplungjan No need to apologize. I just said regex is not your best bet because of the fact that it is hard to maintain and extend the functionality. Also, it is quite slow. No one forces you to not use regex. My code is just as valid and if you write one or two lines it won't even matter. I agree that the number of iterations you do is crucial regarding speed, but still. – F. Müller Mar 30 '21 at 08:36
  • There is absolutely no need to care about speed when you do a few replacements or splits. I would never NOT use a useful method, just because it might be slow when doing 10000 of them. If I am NOT doing 10000 of them, then I prefer readability and terseness. If however the regular expression is hard to read, then I will reconsider. Anyway, I have updated my answer to what I expect OP actually were asking – mplungjan Mar 30 '21 at 08:41
  • 1
    @mplungjan Ikr. I already stated this multiple times. :) The speed is the last thing to worry about - if the regex gets more complicated or has side-effects you have to rewrite the whole functionality again. So you could do it from the start. I had to do this in my job numerous times. The maintainability and scalability of code are really important. That is the real pain-point. As I said it is an alternative. – F. Müller Mar 30 '21 at 08:49
0

The below snippet will remove all the existing + symbols from string.

let str = 'abcd + efg + hij';
str = str.replace(/\+/gm, '');
//output: abcd  efg  hij

For trim use the below snippet. It will remove the spaces from around the string.

let str = "   Hello    World!!   "
str = str.trim();
// output: Hello    World!!

If you want to replace the last + symbol only.

let str = 'abcd + efg + hij';
let lastIndex = str.lastIndexOf('+');

if (lastIndex > -1) {
    let nextString = str.split('');
    nextString.splice(lastIndex, 1, '');
    str = nextString.join('');
}
// output: abcd + efg  hij
Abhisek Dutta
  • 257
  • 2
  • 4