I have a sentence that I would like to have only the last 'and' remaining, and remove the others.
"Lions, and tigers, and bears, and elephants", and I would like to turn this into:
"Lions, tigers, bears, and elephants".
I have tried using a regex pattern like str = str.replace(/and([^and]*)$/, '$1'); which obviously didn't work. Thanks.
Use this regex:
and (?=.*and)
and matches any and followed by a space. Space is matched so it is removed on replacement, to prevent having 2 spaces
(?=.*and) is a lookahead, meaning it will only match if followed by .*and, if followed by and
Use this code:
str = str.replace(/and (?=.*and)/g, '');
You can use a positive look-ahead (?=...), to see if there is another and ahead of the current match. You also need to make the regex global with g.
function removeAllButLastAnd(str) {
return str.replace(/and\s?(?=.*and)/g, '');
}
console.log(removeAllButLastAnd("Lions, and tigers, and bears, and elephants"));
var multipleAnd = "Lions, and tigers, and bears, and elephants";
var lastAndIndex = multipleAnd.lastIndexOf(' and');
var onlyLastAnd = multipleAnd.substring(0, lastAndIndex).replace(/ and/gi, '')+multipleAnd.substring(lastAndIndex);
console.log(onlyLastAnd);
Related
I want to remove << any words #_ from the following string.
stringVal = "<<Start words#_ I <<love#_ kind <<man>>, <<john#_ <<kind man>> is really <<great>> <<end words#_ ";
Result mast be:
Start words I love kind <<man>>, john <<kind man>> is really <<great>> end words
I tried like this:
stringVal = stringVal.replace(/^.*<<.+\#_.*$/g, "");
But it removes all string.
Note: << any words #_ may exists multiple time in string, at the start, in the middle or at the end
Inferring from your examples, you might be looking for:
stringVal = "<<Start words#_ I <<love#_ kind <<man>>, <<john#_ <<kind man>> is really <<great>> <<end words#_ ";
stringVal = stringVal.replace(/<<([-\w ]+)#_/g, "$1");
console.log(stringVal);
To allow other characters, change the \w+ to e.g. [-\w ]+.
See an additional demo on regex101.com.
Instead of using .+\#_, and you want to match any words you could match word characters optionally repeated by matching a space space and word characters.
<<(\w+(?: \w+)*)#_
Regex demo
In the replacement use group 1 $1
Note that you don't have to escape #
const regex = /<<(\w+(?: \w+)*)#_/g;
stringVal = "I <<love#_ kind <<man>>, <<john#_ <<kind man>> is really <<great>>";
const result = stringVal.replace(regex, '$1');
console.log(result);
I'm trying to use a regex in JS to remove the last part of a string. This substring starts with &&&, is followed by something not &&&, and ends with .pdf.
So, for example, the final regex should take a string like:
parent&&&child&&&grandchild.pdf
and match
parent&&&child
I'm not that great with regex's, so my best effort has been something like:
.*?(?:&&&.*\.pdf)
Which matches the whole string. Can anyone help me out?
You may use this greedy regex either in replace or in match:
var s = 'parent&&&child&&&grandchild.pdf';
// using replace
var r = s.replace(/(.*)&&&.*\.pdf$/, '$1');
console.log(r);
//=> parent&&&child
// using match
var m = s.match(/(.*)&&&.*\.pdf$/)
if (m) {
console.log(m[1]);
//=> parent&&&child
}
By using greedy pattern .* before &&& we make sure to match **last instance of &&& in input.
You want to remove the last portion, so replace it
var str = "parent&&&child&&&grandchild.pdf"
var result = str.replace(/&&&[^&]+\.pdf$/, '')
console.log(result)
I have a string of text with HTML line breaks. Some of the <br> immediately follow a number between two delimiters «...» and some do not.
Here's the string:
var str = ("«1»<br>«2»some text<br>«3»<br>«4»more text<br>«5»<br>«6»even more text<br>");
I’m looking for a conditional regex that’ll remove the number and delimiters (ex. «1») as well as the line break itself without removing all of the line breaks in the string.
So for instance, at the beginning of my example string, when the script encounters »<br> it’ll remove everything between and including the first « to the left, to »<br> (ex. «1»<br>). However it would not remove «2»some text<br>.
I’ve had some help removing the entire number/delimiters (ex. «1») using the following:
var regex = new RegExp(UsedKeys.join('|'), 'g');
var nextStr = str.replace(/«[^»]*»/g, " ");
I sure hope that makes sense.
Just to be super clear, when the string is rendered in a browser, I’d like to go from this…
«1»
«2»some text
«3»
«4»more text
«5»
«6»even more text
To this…
«2»some text
«4»more text
«6»even more text
Many thanks!
Maybe I'm missing a subtlety here, if so I apologize. But it seems that you can just replace with the regex: /«\d+»<br>/g. This will replace all occurrences of a number between « & » followed by <br>
var str = "«1»<br>«2»some text<br>«3»<br>«4»more text<br>«5»<br>«6»even more text<br>"
var newStr = str.replace(/«\d+»<br>/g, '')
console.log(newStr)
To match letters and digits you can use \w instead of \d
var str = "«a»<br>«b»some text<br>«hel»<br>«4»more text<br>«5»<br>«6»even more text<br>"
var newStr = str.replace(/«\w+?»<br>/g, '')
console.log(newStr)
This snippet assumes that the input within the brackets will always be a number but I think it solves the problem you're trying to solve.
const str = "«1»<br>«2»some text<br>«3»<br>«4»more text<br>«5»<br>«6»even more text<br>";
console.log(str.replace(/(«(\d+)»<br>)/g, ""));
/(«(\d+)»<br>)/g
«(\d+)» Will match any brackets containing 1 or more digits in a row
If you would prefer to match alphanumeric you could use «(\w+)» or for any characters including symbols you could use «([^»]+)»
<br> Will match a line break
//g Matches globally so that it can find every instance of the substring
Basically we are only removing the bracketed numbers if they are immediately followed by a line break.
Is it possible to use regex to find all words within a sentence that contains a substring?
Example:
var sentence = "hello my number is 344undefined848 undefinedundefined undefinedcalling whistleundefined";
I need to find all words in this sentence which contains 'undefined' and remove those words.
Output should be "hello my number is ";
FYI - currently I tokenize (javascript) and iterate through all the tokens to find and remove, then merge the final string. I need to use regex. Please help.
Thanks!
You can use:
str = str.replace(/ *\b\S*?undefined\S*\b/g, '');
RegEx Demo
It certainly is possible.
Something like start of word, zero or more letters, "undefined", zero or more letters, end of word should do it.
A word boundary is \b outside a character class, so:
\b\w*?undefined\w*?\b
using non-greedy repetition to avoid the letter matching tryig to match "undefined" and leading to lots of backtracking.
Edit switch [a-zA-Z] to \w because the example includes numbers in the "words".
\S*undefined\S*
Try this simple regex.Replace by empty string.See demo.
https://www.regex101.com/r/fG5pZ8/5
you can use str.replace function like this
str = str.replace(/undefined/g, '');
Since there are enough solutions with regular expressions, here is another one - using arrays and simple function that finds occurrence of a string in a string :)
Even though the code looks more "dirty", it actually works faster than regular expression, so it might make sense to consider it when dealing with LARGE strings
var sentence = "hello my number is 344undefined848 undefinedundefined undefinedcalling whistleundefined";
var array = sentence.split(' ');
var sanitizedArray = [];
for (var i = 0; i <= array.length; i++) {
if (undefined !== array[i] && array[i].indexOf('undefined') == -1) {
sanitizedArray.push(array[i]);
}
}
var sanitizedSentence = sanitizedArray.join(' ');
alert(sanitizedSentence);
Fiddle: http://jsfiddle.net/448bbumh/
I need to convert a string like this:
tag, tag2, longer tag, tag3
to:
tag, tag2, longer-tag, tag3
To make this short, I need to replace spaces not preceded by commas with hyphens, and I need to do this in Javascript.
I think this should work
var re = new RegExp("([^,\s])\s+" "g");
var result = tagString.replace(re, "$1-");
Edit: Updated after Blixt's observation.
mystring.replace(/([^,])\s+/i "$1-"); There's a better way to do it, but I can't ever remember the syntax
[^,] = Not a comma
Edit Sorry, didn't notice the replace before. I've now updated my answer:
var exp = new RegExp("([^,]) ");
tags = tags.replace(exp, "$1-");
text.replace(/([^,]) /, '$1-');
Unfortunately, Javascript doesn't seem to support negative lookbehinds, so you have to use something like this (modified from here):
var output = 'tag, tag2, longer tag, tag3'.replace(/(,)?t/g, function($0, $1){
return $1 ? $0 : '-';
});
[^,] - The first character is not comma, the second character is space and it searches for that kind of string
([a-zA-Z] ){1,}
Maybe? Not tested. something like that.