I need to remove substrings containing the word "page=" followed by number.
Ex.
s= "aaaapage=500";
Should be
s = "page=500"
I tried
s = s.replace(/&page=\d/g,"");
and
s = s.replace(/&page=[\d]+/g,"");
to no avail
You can match text before and after while capturing the page=[digits]:
s= "aaaapage=500";
document.write(s.replace(/.*(page=\d+).*/, '$1') + "<br/>");
// or with multiline input
s= "a\na\naapage=500text\nnewline";
document.write(s.replace(/[\s\S]*(page=\d+)[\s\S]*/, '$1'));
This is good when we only have 1 page=[digits].
When we have more, use exec:
var re = /page=\d+/g;
var str = 'apageaaaapage=500apageaaaapage=210';
var m;
while ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
document.write(m[0] + "<br/>");
}
I just realized
s = s.replace(/&page=[\d]+/g,"");
actually works
Just remove all the word chars which exists before page=
s.replace(/\w*(page=\d+)/g,"$1");
Related
I am trying to replace a specific character ( "," -> this is the specific character in my case) in a string only if it's followed by a uppercase letter, but no matter how I try it doesn't work. Does anyone know a good way of doing this ?
const p = 'The ,quick brown ,Fox jumps over the lazy Dog.';
console.log(p.replace(/,([A-Z])/g, 'xxx$1'));
var str1 = "test,Test";
var newstr ;
var index1 = str1.indexOf(',');
if(str1.charAt(index1+1) == str1.charAt(index1+1).toUpperCase()) {
var newstr = str1.substr(0, index1) + "*" + str1.substr(index1+1 , str1.length);
}else {
newstr = str1;
}
console.log(newstr);
I created this regex: /[::].+[^\>]/g
Test:
let str = "<foo::bar>"
let match = str.match(/[::].+[^\>]/g).join('')
console.log(match)
Expected answer : bar
Actual answer : ::bar
Answers appreciated.
One option is to use a lookbehind assertion ((?<=)), which is currently supported only by Chrome & Safari:
const str = "<foo::bar>"
const match = str.match(/(?<=::)[^\>]+/g).join('')
console.log(match)
Another option is to use a capturing group instead of a lookbehind:
::([^>]+)
Regex demo
For example
const regex = /::([^>]+)/g;
const str = `<foo::bar>`;
let m;
let match = [];
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
match.push(m[1]);
}
console.log(match.join(''));
If you want to match the whole pattern of the string, you might use:
<[^>]+::([^>]+)>
Regex demo
const regex = /<[^>]+::([^>]+)>/g;
const str = `<foo::bar>`;
let m;
let match = [];
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
match.push(m[1]);
}
console.log(match.join(''));
Adding an extra match & join to remove '::' had solved the problem.
Working code:
let str = "<foo::bar>"
let match = str.match(/[::].+[^\>]/g).join('')
.match(/[^(::)].+/g).join()
console.log(match)
Im trying to replace a character at a specific indexOf to uppercase.
My string is a surname plus the first letter in the last name,
looking like this: "lovisa t".
I check the position with this and it gives me the right place in the string. So the second gives me 8(in this case).
first = texten.indexOf(" ");
second = texten.indexOf(" ", first + 1);
And with this I replace the first letter to uppercase.
var name = texten.substring(0, second);
name=name.replace(/^./, name[0].toUpperCase());
But how do I replace the character at "second" to uppercase?
I tested with
name=name.replace(/.$/, name[second].toUpperCase());
But it did´t work, so any input really appreciated, thanks.
Your error is the second letter isn't in position 8, but 7.
Also this second = texten.indexOf(" ", first + 1); gives -1, not 8, because you do not have a two spaces in your string.
If you know that the string is always in the format surname space oneLetter and you want to capitalize the first letter and the last letter you can simply do this:
var name = 'something s';
name = name[0].toUpperCase() + name.substring(1, name.length - 1) + name[name.length -1].toUpperCase();
console.log(name)
Here's a version that does exactly what your question title asks for: It uppercases a specific index in a string.
function upperCaseAt(str, i) {
return str.substr(0, i) + str.charAt(i).toUpperCase() + str.substr(i + 1);
}
var str = 'lovisa t';
var i = str.indexOf(' ');
console.log(upperCaseAt(str, i + 1));
However, if you want to look for specific patterns in the string, you don't need to deal with indices.
var str = 'lovisa t';
console.log(str.replace(/.$/, function (m0) { return m0.toUpperCase(); }));
This version uses a regex to find the last character in a string and a replacement function to uppercase the match.
var str = 'lovisa t';
console.log(str.replace(/ [a-z]/, function (m0) { return m0.toUpperCase(); }));
This version is similar but instead of looking for the last character, it looks for a space followed by a lowercase letter.
var str = 'lovisa t';
console.log(str.replace(/(?:^|\s)\S/g, function (m0) { return m0.toUpperCase(); }));
Finally, here we're looking for (and uppercasing) all non-space characters that are preceded by the beginning of the string or a space character; i.e. we're uppercasing the start of each (space-separated) word.
All can be done by regex replace.
"lovisa t".replace(/(^|\s)\w/g, s=>s.toUpperCase());
Try this one (if it will be helpfull, better move constants to other place, due performance issues(yes, regexp creation is not fast)):
function normalize(str){
var LOW_DASH = /\_/g;
var NORMAL_TEXT_REGEXP = /([a-z])([A-Z])/g;
if(!str)str = '';
if(str.indexOf('_') > -1) {
str = str.replace(LOW_DASH, ' ');
}
if(str.match(NORMAL_TEXT_REGEXP)) {
str = str.replace(NORMAL_TEXT_REGEXP, '$1 $2');
}
if(str.indexOf(' ') > -1) {
var p = str.split(' ');
var out = '';
for (var i = 0; i < p.length; i++) {
if (!p[i])continue;
out += p[i].charAt(0).toUpperCase() + p[i].substring(1) + (i !== p.length - 1 ? ' ' : '');
}
return out;
} else {
return str.charAt(0).toUpperCase() + str.substring(1);
}
}
console.log(normalize('firstLast'));//First Last
console.log(normalize('first last'));//First Last
console.log(normalize('first_last'));//First Last
Suppose my text is below:
One of the compelling reasons for buying this phone could be its display. Of course, we would have loved full HD, but then again we shut up because of the punchy price-tag. The screen responsiveness is also good.
I just want to get the index of last occurrence of "the" string in my text.(using RegExp)
var re = new RegExp("\\b"+"the"+"\\b",'g');
var pos = re.lastIndex;
gives only the position of first occurence of the string the..
any suggestions?
Why do you need regex to find last occurence of substring . you can use native .lastIndexOf() method:
re.lastIndexOf("the");
One way;
var pos = -1;
while ((match = re.exec(str)) != null)
pos = match.index;
alert("last match found at " + pos);
The regular expression is /\bthe\b(?!(.|\n)*\bthe\b)/ (no global flag!) ...meaning the word "the" which is not followed by the word "the".
To test:
var re = new RegExp('\\b' + input + '\\b(?!(.|\\n)*\\b' + input + '\\b)');
var pos = re.test(str) ? re.exec(str).index : -1;
Here's a working solution, even with non-global regular expresions:
function regexLastIndexOf(str, regex) {
regex = regex.global
? regex
: new RegExp(regex.source, 'g' + (regex.ignoreCase ? 'i' : '') + (regex.multiLine ? 'm' : ''));
var lastIndexOf = -1;
var nextStop = 0;
var result;
while ((result = regex.exec(str)) != null) {
lastIndexOf = result.index;
regex.lastIndex = ++nextStop;
}
return lastIndexOf;
}
What is an acceptable way to remove a particular trailing character from a string?
For example if I had a string:
> "item,"
And I wanted to remove trailing ','s only if they were ','s?
Thanks!
Use a simple regular expression:
var s = "item,";
s = s.replace(/,+$/, "");
if(myStr.charAt( myStr.length-1 ) == ",") {
myStr = myStr.slice(0, -1)
}
A function to trim any trailing characters would be:
function trimTrailingChars(s, charToTrim) {
var regExp = new RegExp(charToTrim + "+$");
var result = s.replace(regExp, "");
return result;
}
function test(input, charToTrim) {
var output = trimTrailingChars(input, charToTrim);
console.log('input:\n' + input);
console.log('output:\n' + output);
console.log('\n');
}
test('test////', '/');
test('///te/st//', '/');
This will remove trailing non-alphanumeric characters.
const examples = ["abc", "abc.", "...abc", ".abc1..!##", "ab12.c"];
examples.forEach(ex => console.log(ex.replace(/\W+$/, "")));
// Output:
abc
abc
...abc
.abc1
ab12.c