Reputation: 4294
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.
Anyone who knows how I fix this?
Upvotes: 0
Views: 255
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
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