let slug = 'test-value/2';
let slug = 'test-value-data/10';
let slug = 'test-number-data/100';
let slug = 'data-test/1000';
let slug = 'test/10000';
For example, each time I select, I will get 1 slug as above. Now I want to trim the string from /number. For example, I want to trim the string test-value/2 to test-value. So how to cut the string from / onwards. And common to all slugs. Please give me your opinion, Thank you.
Try to replace it using regex as shown in the following example :
let slug='test-value/2'
let trimmedSlug=slug.replace(/\/.*/i,'')
console.log(trimmedSlug)
You can use .split()
Note: Use this method if the slug will always have a format of <slug without '/'>/<number>
// Using .split();
let slug = 'test-value/2';
const trimmedSlug = slug.split('/')[0];
console.log(trimmedSlug);
Related
I am looking to remove any value after ':->' in JavaScript
For example if 'Packet:->3', I would like to store "Packet:->" in the variable so I can use it before the if statement seen below. Pretty much I am looking to remove any digits after '>'
I was trying the below, but did not have much luck.
NTEremoved = NTE.indexOf(':->');
What would be the best way of doing this?
if(NTE == 'Packet:->' || NTE == 'Serving:->' || NTE == 'Can/Carton/Bottle:->'){
}
String split.
const testStr1 = "Packet:->3";
const testStr2 = "BlahBlahBlah278:->Hello hello this is cool";
const result1 = testStr1.split(":->")[0] + ":->"; // split "splits" the string into an array based on the delimiter ":->"; the second part would be 3
const result2 = testStr2.split(":->")[0] + ":->";
console.log(result1);
console.log(result2);
Docs.
I would do something like this, to take care also of edge cases (assuming you don't care about what is coming after the first :->:
let texts = ["Packet:->11", "Cat:->22", "Packet:->:->:->44"];
for (let text of texts) {
console.log(text.replace(/(:->).*$/, "$1"))
}
Since you have mentioned you have tries to use indexOf before but fail to do that, I will provide you a way using a combination of indexOf and String.slice
let string = "Serving:->3"
//Indexof return the first index of an element so you have to add 3 (the length of ":->"
let newstring = string.slice(0,string.indexOf(":->")+3)
console.log(newstring)
So I'm using webSpeechSysthesis to make something that can take inputs and give out results on it with the commands that I have , one command is the "solve" something like "solve √45" and it'll give the answer
I cant figure out how do I separate the √45 and use it to calculate , in Speech synthesis the string that is said is stored in a variable "text"
I tried using replace() and replace the solve with nothing so that I only have numbers and operators but I only get the ' ' , nothing after it
Let word = "solve"
if(text.startsWith(word)){
let final = word.replaceAll(/\bsolve\b/g,'')
Console.log(final)
}
You should use let final = text.replaceAll(/\bsolve\b/g,'') instead of let final = word.replaceAll(/\bsolve\b/g,'').
let text = "solve √45";
let word = "solve";
if(text.startsWith(word)) {
let final = text.replaceAll(/\bsolve\b/g,'');
console.log(final);
};
You don't need to check if a word starts with solve, you can do this with regex as well using the ^ character. There is also no need to use the global flag with replaceAll.
let word = "solve √45";
let final = word.replace(/^solve\b /g, "");
console.log(final);
Here is a working code I have to get a specific portion of a URL string:
const movieName = "frozen_2019";
const courseName = "olaf_is_enjoying_living_his_dream_1";
const source = "your majesty from https://example.com/english/courses/frozen_2019/olaf_is_enjoying_living_his_dream_1/voices/references/translate/do%20you%20hear%20that.mp3";
console.log(getSourceError(source)); // result
function getSourceError(source) {
const a = source.substring(source.indexOf(courseName) + courseName.length + 1);
const b = a.substring(a.lastIndexOf("/"));
return a.replace(b , "");
}
Although it's working as expected but I think there should be a cleaner solution to do this...
As you see I want the string between courseName and the file name at the end of the URl.
I'm not completly sure what you mean by cleaner solution but this is a one-liner line with regex supposing you got the same variable names like in your snippet. Is this what you wanted to achieve? You can trim the last and first character to remove the slashes if needed.
const source = "your majesty from https://example.com/english/courses/frozen_2019/olaf_is_enjoying_living_his_dream_1/voices/references/translate/do%20you%20hear%20that.mp3";
const courseName = "olaf_is_enjoying_living_his_dream_1";
let extracted = source.match("(?<="+courseName+").*\/");
console.log(extracted);
As you see I want the string between courseName and the file name at
the end of the URL.
When manipulating URL strings, it's often a good idea to split the string into an array using:
let myURLArray = myURLString.split('/');
Then, in this situation, you can use:
indexOf()
splice()
join()
to return the section of the URL that you want.
Working Example:
const courseName = "olaf_is_enjoying_living_his_dream_1";
const source = "your majesty from https://example.com/english/courses/frozen_2019/olaf_is_enjoying_living_his_dream_1/voices/references/translate/do%20you%20hear%20that.mp3";
let sourceArray = source.split('/');
let courseNameIndex = sourceArray.indexOf(courseName);
let urlSectionArray = sourceArray.splice((courseNameIndex + 1), ((sourceArray.length - 1) - courseNameIndex - 1));
let urlSection = urlSectionArray.join('/');
console.log(urlSection);
Hi if your source is consinstent with its structure you can split and join the pieces you require.
source.split('/').splice(7,3).join('/')
I have following string:
How can I extract text (i.e.ABC) from the string?
You can try anchorObject.pathname or anchorObject.href.match(/\/([^/]+)$/)[1] if you just want the last path.
You still need to get the anchorObject from the DOM.
const parser = new DOMParser();
const elm = parser.parseFromString('', 'text/html');
const anchorObject = elm.getElementsByTagName('a')[0];
And voilà.
If you are not sure of what the length of the variable you're looking for is, you can use this syntax.
let string = ' ';
console.log(string.split('"')[1].split('/')[3]);
If you know what you're looking for ( for Example: ABC ) you can find index of ABC, and splice the string.
let variable = 'ABC'
console.log(string.substr(string.search("ABC"), variable.length))
Breakdown the string until you get the variable.
My URL looks like this
stackoverflow.com/questions/ask/format/return
I need to get only format/return from the above URL. I'm able to assign the complete URL to a variable. Currently i'm doing it on split
url.split("/")[4]
url.split("/")[5]
And this is not Generic. What is the better way to achieve this?
The shortest, cleanest way to do this is by using slice on the splitted URL:
url.split("/").slice(-2).join("/")
Just use the length to help you index from the end:
var res = url.split('/')
var last = res[res.length-1]
var pre_last = res[res.length-2]
A genetic solution,
Var URL = url.split("/"); //
Last = URL[URL.length-1]; // return
LastBefore = URL[URL.length-1]; //format
url = "stackoverflow.com/questions/ask/format/return"
URL = url.split("/");
console.log(URL[URL.length-1]) // return
console.log(URL[URL.length-2]) //format
Look for the last and penultimate values:
let spl = url.split("/");
alert(spl[spl.length-2]+' and '+spl[spl.length-1]);
I'd parse the url to a URL, then use match on the pathname. This way it will also work should you have any searchparams (?foo=bar) in your url
const s = "https://stackoverflow.com/questions/ask/format/return";
const uri = new URL(s);
const m = uri.pathname.match(/([^\/]*)\/([^\/]*)$/);
console.log(m);
Note that you'll get an array holding three entries - 0 being the path combined, 1 the first and 2 the last param.
You can use a simple regex /.*\/(.*\/.*)/) to extract exactly what you want.
str.match(/.*\/(.*\/.*)/).pop()
var str = "stackoverflow.com/questions/ask/format/return",
res = str.match(/.*\/(.*\/.*)/).pop();
console.log(res);
var parts = url.split("/");
lastTwo = [parts.pop(), parts.pop()].reverse().join("/");