Remove text between first and last brakets - javascript

My original string :
[Abc ![](https://i.imgur.com/5AteeJf.png)](https://quiz.com?/quiz_id=2/quiz_name=15/level=null)
i tried with this javascript formula but no luck
string.replace(/ *\[[^\]]*]/, '')
How can i remove string between first [ and last ]?
Thank you so much
My desired output is url
https://quiz.com?/quiz_id=2/quiz_name=15/level=null

Just use .* instead of [^\]]*, so the match won't stop at the first ].
let string = '[Abc ![](https://i.imgur.com/5AteeJf.png)](https://quiz.com?/quiz_id=2/quiz_name=15/level=null)';
let result = string.replace(/\[.*\]/, '');
console.log(result);

You can use match method with /\[.*?\]\((.*)\)/ regex. to get the text after opening and closing the square bracket and between parenthesis.
const str = '[Abc ![](https://i.imgur.com/5AteeJf.png)](https://quiz.com?/quiz_id=2/quiz_name=15/level=null)'
const [_, value] = str.match(/\[.*\]\((.*)\)/);
console.log(value)

The regular expression you were using was using only up to the first ']'. This regular expression should do it:
[.*]
let sentence = "[Abc ![](https://i.imgur.com/5AteeJf.png)](https://quiz.com?/quiz_id=2/quiz_name=15/level=null)";
let extractedSentence = sentence.replace(/\[.*\]/, "");

Related

code to replace all spaces except the first and last with %20

urlEncode = function(text) {
let str = text.split(' ').join('%20');
return str;
};
The above is working but If a string has a space in the beginning or end it should not replace %20 .The above is replacing every space .I tried using loops ..
for(let i = 1 ;i < text.length-1;i++){
if(text[i]===''){
text[i]='%20';
}
}
return text;
this one is returning the original text with no change.
A regular expression to match a space not at the beginning nor end of the string would work.
const urlEncode = text => text.replace(/(?!^) (?!$)/g, '%20');
(?!^) - not at the beginning
(?!$) - not at the end
Another method would be to turn the text string into an array so that assignment to its indicies using your second snippet would work. Replace the indicies as needed, then join into a string again and return.
or, you can test another
const urlEncode = text => text.replace(/[^\s]\s[^\s$]/g, '%20')

String Remove Everything after Last Hyphen

Is there a way in JavaScript to remove everything after last hyphen if its a number?
product-test-grid-2
So Result would be only:
product-test-grid
Trying to use this resource:
Remove everything after a certain character
You can use a simple regular expression with replace.
eg..
/-\d+$/ = a dash followed by 1 or more numbers \d+, that's at the end $
const reLast = /-\d+$/;
const test1 = 'product-test-grid-2';
const test2 = 'product-test-grid-nan';
console.log(test1.replace(reLast, ''));
console.log(test2.replace(reLast, ''));
Simple JS, No regex involved
const label = 'product-test-grid-2'.split('-');
!isNaN(+label[label.length - 1]) ? label.pop() : '';
console.log(label.join('-'));
// you can encapsulate it into function
function formatLabel(label) {
label = label.split('-');
!isNaN(+label[label.length - 1]) ? label.pop() : '';
return label.join('-');
}
// 2 should be removed at the end
console.log(formatLabel('product-test-grid-2'));
// two should be left untouched
console.log(formatLabel('product-test-grid-two'));
'product-test-grid-2'.replace(/(?<=-)\d*$/, '') will preserve the last hyphen.
'product-test-grid-2'.replace(/-\d*$/, '') will remove it.
Split by "-", check if last item is a number: pop if it is, join with "-":
sentence="product-test-grid-2";
words=sentence.split("-");
if(words[words.length-1].match(/^\d+$/)) words.pop();
result=words.join("-");
console.log(result);
You can do this with regrx but it seems to me Overkill
I would do that
const str='product-test-grid-2'
const pos=str.lastIndexOf('-')
const res=str.slice(0,pos)
console.log(res)

How to keep only the doube quote part in a string in Javascript?

I want to keep only the double quote part of a string in javascript. Suppose this is my string:
const str = 'This is an "example" of js.'
I want my result like that:
output = example
Means I want to keep only the example part which is in the double quote.
I can remove the double quote from string but I haven't found any good way to keep only the double quote part of a string.
Get the start and last index of " and then use slice.
const str = 'This is an "example" of js';
const startIdx = str.indexOf('"');
const lastIdx = str.lastIndexOf('"');
const output = str.slice(startIdx+1, lastIdx);
console.log(output);
As noted in the comments, this is not a valid string, you need to escape inner double quotes const str = "This is an \"example\" of js."
After that you can extract the value inside the quotes with a regex:
const matches = str.match(/"(.*?)"/);
return matches ? matches[1] : str;
you could use a regex capturing group like so:
const captured = str.match(/\"(.*)\"/)
but you'll need to declare the string with single quotes and then double quotes inside like this:
const str = 'This is an "example" of js.'
try it here: https://regexr.com/4hfh3

RegEx - Parse through string for specific words

I'm looking to parse through a string and find all the handles (#name) and push them each into one array (without the # though) so I can loop through them (with forEach) and send them each an alert. Each handle is separated by a space.
If you just need to extract the users from a tweet, you can use the following regex:
/#([a-zA-Z0-9]+)/g
For example:
var string = '#JohnSmith #DylanThompson Hey guys!';
var numberPattern = /#([a-zA-Z0-9]+)/g;
var res = string.match(numberPattern);
console.log(res);
This would spit out:
["#JohnSmith", "#DylanThompson"]
You can capture #followedByName and than replace #
let str = `#someName hey #someMoreNames`
let op = str.match(/(^|\s)#\w+/g).map(e=>e.trim().replace(/#/g,''))
console.log(op)
try
let str= "Here #ann and #john go to #jane";
let m= str.match(/#\w+/g).map(x=>x.replace(/./,''));
m.forEach(x=> console.log(x));
You can use also positive lookbehind regexp but it is not supported by firefox yet (but it is part of ES2018):
let str= "Here #ann and #john go to #jane";
let m= str.match(/(?<=#)\w+/g);
m.forEach(x=> console.log(x));
where (?<=#)\w+ match word which start after # (excluding this char - positive lookbehind)
You can combine match to extract names and slice to remove #:
str = "#JohnSmith #DylanThompson Hey guys";
let arr = str.match(/#\w+/g).map(e=>e.slice(1));
console.log(arr);
Try This:
var str= "Here #ann and #john go to #jane";
var patt = /#(\w+)/g;
while ( (arr = patt.exec(str)) !== null ) { console.log(arr[1]); }

How can I remove all characters up to and including the 3rd slash in a string?

I'm having trouble with removing all characters up to and including the 3 third slash in JavaScript. This is my string:
http://blablab/test
The result should be:
test
Does anybody know the correct solution?
To get the last item in a path, you can split the string on / and then pop():
var url = "http://blablab/test";
alert(url.split("/").pop());
//-> "test"
To specify an individual part of a path, split on / and use bracket notation to access the item:
var url = "http://blablab/test/page.php";
alert(url.split("/")[3]);
//-> "test"
Or, if you want everything after the third slash, split(), slice() and join():
var url = "http://blablab/test/page.php";
alert(url.split("/").slice(3).join("/"));
//-> "test/page.php"
var string = 'http://blablab/test'
string = string.replace(/[\s\S]*\//,'').replace(/[\s\S]*\//,'').replace(/[\s\S]*\//,'')
alert(string)
This is a regular expression. I will explain below
The regex is /[\s\S]*\//
/ is the start of the regex
Where [\s\S] means whitespace or non whitespace (anything), not to be confused with . which does not match line breaks (. is the same as [^\r\n]).
* means that we match anywhere from zero to unlimited number of [\s\S]
\/ Means match a slash character
The last / is the end of the regex
var str = "http://blablab/test";
var index = 0;
for(var i = 0; i < 3; i++){
index = str.indexOf("/",index)+1;
}
str = str.substr(index);
To make it a one liner you could make the following:
str = str.substr(str.indexOf("/",str.indexOf("/",str.indexOf("/")+1)+1)+1);
You can use split to split the string in parts and use slice to return all parts after the third slice.
var str = "http://blablab/test",
arr = str.split("/");
arr = arr.slice(3);
console.log(arr.join("/")); // "test"
// A longer string:
var str = "http://blablab/test/test"; // "test/test";
You could use a regular expression like this one:
'http://blablab/test'.match(/^(?:[^/]*\/){3}(.*)$/);
// -> ['http://blablab/test', 'test]
A string’s match method gives you either an array (of the whole match, in this case the whole input, and of any capture groups (and we want the first capture group)), or null. So, for general use you need to pull out the 1th element of the array, or null if a match wasn’t found:
var input = 'http://blablab/test',
re = /^(?:[^/]*\/){3}(.*)$/,
match = input.match(re),
result = match && match[1]; // With this input, result contains "test"
let str = "http://blablab/test";
let data = new URL(str).pathname.split("/").pop();
console.log(data);

Categories

Resources