TheYaXxE
TheYaXxE

Reputation: 4294

Replace a word with plus-sign

When I'm trying to remove a certain word from an input, it removes the first time that specific word occurs in the input (also if the word is a part of another word).

But what I want to do, is only remove the word I wrote where it is the full word, and not if it is a part of another one.

This is my code:

HTML:

<input value="c++ c+ c" />

JavaScript:

$input = $('input');
$word = "c+";

$input.val( $input.val().replace($word, "") );

The output of this will be:

+ c+ c // Removed the "c+" part of the "c++" word

..but want it to be:

c++ c // Removed "c+"

I have tried to use a regex /\bc+\b/g but that seems to remove every occurrences of that word. But if I want to remove a word without a +-sign, the above code works fine. I know that when using + and other signs, you should escape it, but that I've also tried with no luck.

$input.val( $input.val().replace(/\bc\+/, "") );
// Output: + c+ c // Removed the "c+" part of the "c++" word

Here it is replacing the first part of "c++" like in the first example.

Live Fiddle

Anyone who knows how I fix this?

Upvotes: 0

Views: 255

Answers (3)

jdphenix
jdphenix

Reputation: 15425

This allows you to construct a RegExp from your input, and replace matches that are between spaces, or at the beginning or end of the string.

RegExp.escape = function(s) {
  return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
};

var value = 'c+ c++ c+ c+c c+ c',
  $word = RegExp.escape('c+'),
  regex = new RegExp('(?:^|\\s+)' + $word + '(?:\\s+|$)', 'g');

$('input').val(value);
$('input').val($('input').val().replace(regex, ' '));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input></input>

Upvotes: 1

leopik
leopik

Reputation: 2351

Try with

str.replace(/\bc\+(?=\s|$)/g, "");

Note the /g at the end - that means replacing all occurences.

EDIT: As mentioned in keune's answer you should check that c+ is followed by a space (\s) or it is end of a string ($)

Upvotes: 0

keune
keune

Reputation: 5795

I think this will work;

/\bc\+(?=\s|$)/g

This will catch plus characters if they are followed by a space or at the end of the string.

Fiddle here

Upvotes: 1

Related Questions