Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I have a situation to manipulate a given string which is separated by comma and reverse the given string.
Input: hello,world,wow
Expected Output: wow,world,hello
First split the string by the comma. Then reverse the array. Then turn it back into a string.
let foo = 'hello,world,wow' // assign the string
foo = foo.split(',') // splits by comma
foo = foo.reverse() // reverses the array
foo = foo.join() // converts array back into a comma separated string
var initialString = "hello,world,wow"
var finalString = initialString.split(",").reverse().join(",");
console.log(finalString) // "wow,world,hello"
Here is the solution to reverse the given string.
let str = "hello,world,wow";
let temp = str.split(",");
let output = "";
// Index will starting from last element
let index = (temp.length - 1);
for(let k=0; k<temp.length; k++){
if(k == (temp.length - 1)){
// Last Element so no need of comma
output += temp[index];
}
else {
// Adding commas to the output
output += temp[index]+",";
}
index--;
}
alert(output);
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 days ago.
Improve this question
I want to split the string below by a default comma which is , and ignore the "," part.
Has anyone come up with a solution for this? Tried a bunch of solutions, but doesn't work.
My string: (testing","a framework), hello world, testing","antother_framework
expected result:
["testing","a framework", "hello world", "testing","antother_framework]
not the nicest way, with regex you could grouped the replace but it works
const str = '(testing","a framework), hello world, testing","antother_framework';
let arr = str.split(',');
console.log(arr);
for (let i = 0; i < arr.length; i++) {
arr[i] = arr[i].replaceAll('(', '');
arr[i] = arr[i].replaceAll(')', '');
arr[i] = arr[i].replaceAll('\"', '');
arr[i] = arr[i].trim();
}
console.log(arr);
You could use this function:
function splitByCommas(str) {
return str.split(/,(?=(?:[^"]*"[^"]*")*[^"]*$)/);
}
Explanation:
/,(?=(?:[^"]"[^"]")[^"]$)/ -> match the comma outside of the quotes
(?:[^"]"[^"]")* -> match the quotes and the text inside the quotes
[^"]*$ -> match the remaining text after the last quote
If you run the function like this:
console.log(splitByCommas('(testing","a framework), hello world, testing","antother_framework'));
It will give the following output:
[
'(testing","a framework)',
' hello world',
' testing","antother_framework'
]
If you want to also trim the whitespaces, you can use this:
function splitByCommas(str) {
return str.split(/,(?=(?:[^"]*"[^"]*")*[^"]*$)/).map(function (item) {
return item.trim();
}
);
}
For the same input giving you:
[
'(testing","a framework)',
'hello world',
'testing","antother_framework'
]
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have this particular string :
TOYIN KEMIOGS/OYO/2277TGOGSLAGOS
from this string containing 2 '/'
I want it to extract from wherever we have OGS and stop at wherever we have OGS. OGS always start and end my extracted string
I want an extracted result like this
OGS/OYO/2277TGOGS
Thanks so much
You can achieve it but as a string between first occurrence and last occurrence of OGS as follows:
var a = 'TOYIN KEMIOGS/OYO/2277TGOGSLAGOS';
console.log(a.slice(a.indexOf("OGS"),a.lastIndexOf("OGS")) +"OGS");
You can use match method of string to extract the data required.
const str = "TOYIN KEMIOGS/OYO/2277TGOGSLAGOS";
const result = str.match(/OGS.*OGS/); // Its greedy in nature so you can also use /OGS.*?OGS/
console.log(result[0]);
let str = "TOYIN KEMIOGS/OYO/2277TGOGSLAGOS";
let phrase = "OGS";
let start = str.indexOf(phrase);
let end = str.lastIndexOf(phrase) + phrase.length;
let newStr = str.slice(start, end);
console.log(newStr);
You can treat the start/stop sequences as non-matching groups:
const str = 'TOYIN KEMIOGS/OYO/2277TGOGSLAGOS';
const [match] = str.match(/(?:OGS).+(?:OGS)/);
console.log(match); // "OGS/OYO/2277TGOGS"
If you don't want to keep the start/stop sequences ("OGS"), you can treat them as positive lookbehind/lookaheads:
const str = 'TOYIN KEMIOGS/OYO/2277TGOGSLAGOS';
const [match] = str.match(/(?<=OGS).+(?=OGS)/);
console.log(match); // "/OYO/2277TG"
Here is a string manipulation version, which captures the first and last index.
const extractBetween = (str, marker) =>
str.slice(str.indexOf(marker),
str.lastIndexOf(marker) + marker.length);
const str = 'TOYIN KEMIOGS/OYO/2277TGOGSLAGOS';
const match = extractBetween(str, 'OGS');
console.log(match); // "OGS/OYO/2277TGOGS"
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
i have a variable and I want to separate the name whit a space letter by letter and then UpperCase the letters
var name = "Tom Hanks";
console.log(name) has to be equal to "T O M H A N K S"
var name = "Tom Hanks";
var result = name.toUpperCase().split("").join(" ").replace(/\s+/g, " ");
console.log(result);
First you must split the string to separate the letters of the word and save 'em in a array object. For that you can use the String.split() function:
const myString = 'Tom Hanks';
const splittedString = myString.split('');
Then you can use Array.join() function to create a new string with spaces between the letters of the previous array:
const stringWithSpaces = splittedString.join(' ');
Finally you can use the String.toUpperCase() to set the "caps lock" on:
stringWithSpaces.toUpperCase();
So, here is the complete snippet:
const myString = 'Tom Hanks';
const splittedString = myString.split('');
const stringWithSpaces = splittedString.join(' ');
const upperCaseStringWithSpaces = stringWithSpaces.toUpperCase();
console.log(upperCaseStringWithSpaces);
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 years ago.
Improve this question
I have this code:
var str = 'country/city/area'
var idx = str.lastIndexOf('country/city')
// idx = 0
And idx is always 0. Shouldn't idx be 12? My goal is to use it substr() in order to take the string 'area' out of the str.
var str = 'country/city/area'
var pattern = 'country/city/'
var idx = str.lastIndexOf(pattern) + pattern.length
var substring = str.substring(idx, str.length)
Explanation
1) Define the pattern you are searching for
2) Find the beginning of the pattern and add the length of the pattern => now you are at the end
3) Copy the part behind the pattern to the end of the string
if you want to get the last word, you can search for the last forward slash and get everything after it:
str.substr(str.lastIndexOf('/') + 1)
if you want to get everything after 'country/city/' but for example you don't know if this the first part of the string, you can use
str.substr(str.indexOf('country/city/') + 13);
it's not 100% clear from your question, what exactly you are trying to achieve though.
You're going to want to add the length of the string that you search for:
var str = 'country/city/area';
var checkStr = 'country/city';
var idx = str.lastIndexOf(checkStr);
var lastCharIndex = idx + checkStr.length;
// idx = 0
// idx = 12
note - it would be 12, not 13, because you didn't include the final "/" in your lastIndexOf parameter.
May be you can achieve your goal as follows;
var str = 'country/city/area',
newStr = str.replace("/area","");
console.log(newStr);
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
I have a requirement to remove last n characters from string or remove 'page' from a particular string.
Eg:
var string = 'facebookpage';
Expected output string = 'facebook'
I would like to remove 'page' from the string.
Done it using substring.
var str = "facebookpage";
str = str.substring(0, str.length - 4);
Could you help me to find some better way to do it.
Regex for this:
//str - string;
//n - count of symbols, for return
function(str, n){
var re = new RegExp(".{" + n + "}","i");
return str.match(re);
};
EDIT:
For remove last n characters:
var re = new RegExp(".{" + n + "}$","i");
return str.replace(re, "");
UPDATE:
But use regex for this task, not good way; For example, AVG Runtime for 100000 iterations:
Str length solution = 63.34 ms
Regex solution = 172.2 ms
Use javascript replace function
var str = "facebookpage";
str = str.replace('page','');
You can use this regular expression :
(.*)\\w{4}
code :
var regex =(new RegExp("(.*)\\w{4}"))
val output = regex .exec("facebookpage")
// output is : ["facebookpage", "facebook"]
// output[1] is the Expected output which you want.
Hope this helps.