Javascript replace string which doesn't match? - javascript

Say I have this string:
cat hates dog
When i do a replace :
str = str.replace('cat', 'fish');
I will only get "cat" replaced by "fish" , how to get it works like this:
"cat" replaced by "fish"
"other string"(else) replaced by "goat"
so I will get new string:
fish goat goat

You can use this regexp \b\w+?\b:
"cat hates dog".replace(/\b\w+?\b/g, function(a) {
return a === 'cat' ? 'fish' : 'goat';
});
It will match every word (sequence of word characters \w surrounded by word boundary \b) and pass match results in replace callback;
Output:
fish goat goat

Related

How to remove a single letter word in a string by javascript?

My original string = A abc, B xyz, C mlk ooo
How can I remove single letter of each element: A B C?
Expected Output = abc, xyz, mlk ooo
You could use a regex to replace a single letter (indicated by a letter with a word-break \b on either side of it) followed by some number of spaces with nothing:
const str = "A abc, B xyz, C mlk ooo"
const output = str.replace(/\b[a-z]\b\s*/ig, '', str)
console.log(output)
Regex demo on regex101

Regex to match full words, but no match at all on first failure

I'm looking for a JS regex to match full words, but not to match at all if there is any different word (any failure).
Eg: Match for \b(dog|cat)\b
cat dog cat --> everything is matched. OK.
dog --> dog is matched even if cat does not exist here. OK.
dog cata --> dog is matched, cata not. I don't want any match at all.
Is that ^(?:(?=.*\bdog\b)(?=.*\bcat\b).*|cat|dog)$ what you want?
Explanation:
^ : beginning of the string
(?: : start non capture group
(?=.*\bdog\b) : positive lookahead, zero-length assertion, make sure we have dog somewhere in the string
(?=.*\bcat\b) : positive lookahead, zero-length assertion, make sure we have cat somewhere in the string
.* : 0 or more any character
| : OR
cat : cat alone
| : OR
dog : dog alone
) : end group
$ : end of string
var test = [
'dog cat',
'cat dog',
'dog',
'cat',
'dog cata',
'cat fish',
];
console.log(test.map(function (a) {
return a + ' ==> ' + a.match(/^(?:(?=.*\bdog\b)(?=.*\bcat\b).*|cat|dog)$/);
}));
So, basically you want to check all of your words in your string matches the regexor all of your string should be from a list of string, isn't it? Let's split all the words and check whether all of them belongs from your list of strings.
var reg = /dog|cat|rat/,
input1 = "dog cat rat",
input2 = "dog cata rat",
input3 = "abcd efgh",
isMatched = s => !(s.match(/\S+/g) || []).some(e => !(new RegExp(e).test(reg)));
console.log(isMatched(input1));
console.log(isMatched(input2));
console.log(isMatched(input3));

Regex: Match desired chars at the beginning/end of string

I need a regex to match exactly 'AB' chars set at the beginning or at the end of the string and replace them with ''. Note: it should not match parts of that chars set, only if it occurs whole.
So if I have 'AB Some AB company name AB', it should return 'Some AB company name'.
If I have 'Balder Storstad AB', it should remove only 'AB' and not the 'B' at the beginning because it is not whole 'AB', only the part of it.
What I tried is:
name.replace(/^[\\AB]+|[\\AB]+$/g, "");
And it is OK until single "A" or "B" encountered at the beginning or end of the string. If test string is 'Balder Storstad AB' it matches both 'B' at the beginning and 'AB' at the end and returns 'alder Storstad'. It should skip single 'B' or single 'A' at the beginning or end.
What is wrong in my regex?
EDIT:
I forgot to add this. If test strings are:
"ABrakadabra AB" or "Some text hahahAB" or "ABAB text text textABAB"
"AB" should not be matched because they are not separate "AB" groups but part of other word.
var rgx = /(^AB\s+)|(\s+AB$)/g;
console.log("AB Some AB company name AB".replace(rgx, ""));
console.log("Balder Storstad AB".replace(rgx, ""));
console.log("ABrakadabra AB".replace(rgx, ""));
console.log("Some text hahahAB".replace(rgx, ""));
console.log("ABAB text text textABAB".replace(rgx, ""));
Explanation :
(^AB\s+) // AB at the beginning (^) with some spaces after it
| // Or
(\s+AB$) // AB at the end ($) with some spaces before it

.split() on elements of a sentence string, advanced separator

I want to be able to split a sentence string into an array of individual word strings.
sentenceArr = 'I take the dog to the park'
sentenceArr.split(' ');
Desired result: ['I', 'take', 'the', 'dog', 'to', 'the', 'park']
This is easy if they are just split by spaces as above, but if there are commas or double spaces, or RegExes in the string it can come unstuck.
sentenceArr = 'I take,the dog to\nthe park'
sentenceArr.split(' ');
How can I modify the split() separator argument to account for these irregularities?
Ideally, I want to be able to split anywhere there isn't a letter.
split also takes a regex as argument :
sentenceArr = 'I take,the dog to\nthe park'
var r= sentenceArr.split(/\W+/);
console.log(r)

Match a word with space beside

I'm trying to match the following examples (javascript):
1.- "dog dogs"
R- match dog = true
2.- "dogsdogs"
R- match dog= false
3.- "cat dog dogs dogdogs dog"
R - match dog(twice) = true
4.- "cat dog$dog"
R- match dog= false
5.- "cat dog\ndog" OR "cat dog\sdog"
R- match dog(twice) = true
6.- "catdog dog $dog$dog dog"
R- math dog(twice) = true
I've just got this /\b(dog)\b/g but if i use this /^(dog)$/g just match one word
Thanks in advance
Try this:
/(^|\s)(dog)(?=\s|$)/gm
Tested via regexr - http://regexr.com?38gla
This matches a start of string or whitespace, then the word dog, then whitespace or end of string. The trailing whitespace/end of string is a positive lookahead, so its not consumed, allowing that space to be used for another match - ex "cat dog dog"

Categories

Resources