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 4 years ago.
Improve this question
I would like to split a string between these ''' characters.
My string looks like this:
const str = " My random text '''tag1''' '''tag2''' ";
and the output should look like this: ["tag1", "tag2"]
Use a regular expression with a capture group and RegEx.exec() to extract any substrings between three apostrophes. The pattern uses lazy matching (.*?) to match any sequence of characters (including none) between the apostrophes.
const str = " My random text '''tag1''' '''tag2''' ";
re = /'''(.*?)'''/g;
matches = [];
while (match = re.exec(str)) {
matches.push(match[1]);
}
console.log(matches);
Output
[ 'tag1', 'tag2' ]
I think a short and sweet method would be :
var regex = /(?<=''')\w+(?=''')/mgi;
var matches = "My random text '''tag1''' '''tag2'''".match(regex);
with a result of : (2) ["tag1", "tag2"]
It matches everything between any occurence of '''.
You can use a function like this:
function getBetween(content, start, end) {
var result = [];
var r = content.split(start);
for (var i = 1; i < r.length; i++) {
result.push(r[i].split(end)[0]);
if (i < r.length - 1) { i++; }
}
return result;
}
Usage:
var result = getBetween(str, "'''", "'''");
which results in
["tag1", "tag2"]
Proof
const str1 = " My random text '''tag1''' '''tag2''' ";
const str2 = "String '''tag1''' this will work '''tag2'''.";
const str3 = "'''tag1''' '''tag2''' sup man '''tag3'''";
function getBetween(content, start, end) {
var result = [];
var r = content.split(start);
for (var i = 1; i < r.length; i++) {
result.push(r[i].split(end)[0]);
if (i < r.length - 1) { i++; }
}
return result;
}
var result1 = getBetween(str1, "'''", "'''");
var result2 = getBetween(str2, "'''", "'''");
var result3 = getBetween(str3, "'''", "'''");
console.log(result1);
console.log(result2);
console.log(result3);
Hope this helps
Try using template literal like below:
str.split(`'''`);
The result may look like this:
[" My random text ", "tag1", " ", "tag2", " "]
Hope this help ;)
Related
I am very new to coding. I am having issue solving this following:
taking a data block ex:
1963;john, doe;Williwanka,tp;jane;4200;1300;19.63;-42
and covert into something like
1963,"john, doe","Williwanka,tp",jane,4200,1300,19.63,-42
I know I can use split() and join() however having trouble sorting through the string separated by comma "," and add double quote.
let text = "00077;Jessica;Williamsburg,ky;40769;42;42;42;42";
var myArray = text.split(";");
var newText = "";
for (var i = 0; i <= myArray.length; i++) {
if (myArray.indexOf(i) == ",") {
let newText = '"' + fruits.join('","') + '"';
} else {
newText += text.index(i);
}
}
return newText
Split by semicolons, then for each part, check if it includes a comma. If it does, wrap it in quotes, otherwise, don't change it. Then join the result into a string.
const text = "1963;john, doe;Williwanka,tp;jane;4200;1300;19.63;-42";
const parts = text.split(";");
const result = parts.map((p) => p.includes(",") ? `"${p}"` : p).join(",");
console.log(result);
You could use the regex /([^;]+)(?:;|$)/ and replace the first capturing group with " if it cannot be parsed to a number.
const input = "1963;john, doe;Williwanka,tp;jane;4200;1300;19.63;-42",
replacer = (_, p1) => isNaN(p1) ? `"${p1}",` : `${p1},`,
output = input.replace(/([^;]+)(?:;|$)/g, replacer).slice(0, -1);
console.log(output)
While the previous answers are correctly fine, it might be hard to understand how they work for a novice programmer.
Allow me to fix give you another answer below which is based on a simple loop like the OPs original code.
let text = "00077;Jessica;Williamsburg,ky;40769;42;42;42;42";
var partsArray = text.split(";");
var newText = "";
for (var i = 0; i < partsArray.length; i++) {
let onePart = partsArray[i];
if (onePart.includes(",")) {
newText += `"${onePart}"`;
} else {
newText += onePart;
}
newText += ",";
}
console.log(newText);
This question already has answers here:
Capitalize the first letter of every word
(9 answers)
Closed 3 years ago.
I'm writing a bot for discord and using this project to teach myself javascript. I have a predefined string set to message variable and I want this to script to change the first letter of each word in the string to a capital, but so far the function is only returning the message as it was spelt. I cannot understand why
var string = message.substr(message.indexOf(" ")+1);
function capital_letter(str)
{
str=str.split(" ");
for (var i = 0, x = str.length; i<x, i++;)
{
str[i] = str[i].charAt(0).toUpperCase() + str[i].substr(1);
};
return str.join(" ");};
If message = "ring of life" I would expect the output to be "Ring Of Life"
You had some syntax errors, here's a corrected version of your captial_letter function:
function capital_letter (str) {
str = str.split(' ')
for (var i = 0; i < str.length; i++) {
const firstChar = str[i].charAt(0)
str[i] = firstChar.toUpperCase() + str[i].substr(1)
};
return str.join(' ')
};
The biggest one was to separate your loop parameters using ; instead of ,:
for (var i = 0; i < str.length; i++)
p.s. looks like you might benefit from a better IDE :-)
you can try this.
str.toLowerCase().replace(/\b\w{3,}/g, function (l) {
return l.charAt(0).toUpperCase() + l.slice(1);
});
This question already has answers here:
How to remove text from a string?
(16 answers)
Closed 5 years ago.
Suppose my string is like:
var str = "USA;UK;AUS;NZ"
Now from some a source I am getting one value like:
country.data = "AUS"
Now in this case I want to remove "AUS" from my string.
Can anyone please suggest how to achieve this.
Here is what I have tried:
var someStr= str.substring(0, str.indexOf(country.data))
In this case I got the same result.
var str = "USA;UK;AUS;NZ"
console.log(str + " <- INPUT");
str = str.split(';');
for (let i = 0; i < str.length; i++) {
if (str[i] == 'AUS') {
str.splice(i, 1);
}
}
console.log(str.join(';') + " <- OUTPUT");
You can use split and filter:
var str = "USA;UK;AUS;NZ"
var toBeRemoved = "AUS";
var res = str.split(';').filter(s => s !== toBeRemoved).join(';');
console.log(res);
Try this :
var result = str.replace(country.data + ';','');
Thanks to comments, this should work more efficently :
var tmp = str.replace(country.data ,'');
var result = tmp.replace(';;' ,';');
You can use replace() with a regex containing the searched country, this is how should be the regex /(AUS;?)/.
This is how should be your code:
var str = "USA;UK;AUS;NZ";
var country = "AUS";
var reg = new RegExp("("+country+";?)");
str = str.replace(reg, '');
console.log(str);
This will remove the ; after your country if it exists.
Here is a good old split/join method:
var str = "USA;UK;AUS;NZ;AUS";
var str2 = "AUS";
var str3 = str2 + ";";
console.log(str.split(str3).join("").split(str2).join(""));
I'm working to update this function which currently takes the content and replaces any instance of the target with the substitute.
var content = textArea.value; //should be in string form
var target = targetTextArea.value;
var substitute = substituteTextArea.value;
var expression = new RegExp(target, "g"); //In order to do a global replace(replace more than once) we have to use a regex
content = content.replace(expression, substitute);
textArea.value = content.split(",");
This code somewhat works... given the input "12,34,23,13,22,1,17" and told to replace "1" with "99" the output would be "992,34,23,993,22,99,997" when it should be "12,34,23,13,22,99,17". The replace should only be performed when the substitute is equal to the number, not a substring of the number.
I dont understand the comment about the regex needed to do a global replace, I'm not sure if that's a clue?
It's also worth mentioning that I'm dealing with a string separated by either commas or spaces.
Thanks!
You could do this if regex is not a requirement
var str = "12,34,23,13,22,1,17";
var strArray = str.split(",");
for(var item in strArray)
{
if(strArray[item] === "1")
{
strArray[item] = "99"
}
}
var finalStr = strArray.join()
finalStr will be "12,34,23,13,22,99,17"
Try with this
var string1 = "12,34,23,13,22,1,17";
var pattern = /1[^\d]/g;
// or pattern = new RegExp(target+'[^\\d]', 'g');
var value = substitute+",";//Replace comma with space if u uses space in between
string1 = string1.replace(pattern, value);
console.log(string1);
Try this
target = target.replace(/,1,/g, ',99,');
Documentation
EDIT: When you say: "a string separated by either commas or spaces"
Do you mean either a string with all commas, or a string with all spaces?
Or do you have 1 string with both commas and spaces?
My answer has no regex, nothing fancy ...
But it looks like you haven't got an answer that works yet
<div id="log"></div>
<script>
var myString = "12,34,23,13,22,1,17";
var myString2 = "12 34 23 13 22 1 17";
document.getElementById('log').innerHTML += '<br/>with commas: ' + replaceItem(myString, 1, 99);
document.getElementById('log').innerHTML += '<br/>with spaces: ' + replaceItem(myString2, 1, 99);
function replaceItem(string, needle, replace_by) {
var deliminator = ',';
// split the string into an array of items
var items = string.split(',');
// >> I'm dealing with a string separated by either commas or spaces
// so if split had no effect (no commas found), we try again with spaces
if(! (items.length > 1)) {
deliminator = ' ';
items = string.split(' ');
}
for(var i=0; i<items.length; i++) {
if(items[i] == needle) {
items[i] = replace_by;
}
}
return items.join(deliminator);
}
</script>
Having trouble coming up with code doing this.
So for example here is my string.
var str = "Hello how are you today?";
How would I manipulate this string to return the position of the first letter of each word using a loop?
this will give you the result with less complicated code and a single loop
function foo(str) {
var pos = [];
var words = str.split(' ');
pos.push(1);
var prevWordPos;
for (var i = 1; i < words.length; i++) {
prevWordPos = pos[i - 1] + words[i - 1].length;
pos.push((str.indexOf(words[i], prevWordPos) + 1));
}
return pos;
}
You should search for a question before asking it in case it's already been asked and answered.
Get first letter of each word in a string, in Javascript
You can use a regexp replace passing a function instead of a replacement string, this will call the function for each match:
str.replace(/[^ ]+/g, function(match, pos) {
console.log("Word " + match + " starts at position " + pos);
});
The regexp meaning is:
[^ ]: anything excluding space
+: one or more times
"g" option: not only first match, but each of them
in other words the function will be called with sequences of non-spaces. Of course you can define what you consider a "word" differently.
Here is a Solution with two Loops, i hope that is close enough ;)
var starts = [];
var str = "How are you doing today?";
//var count = 0;
var orgStr = str;
while (str.indexOf(" ") > 0) {
if (starts.length > 0) {
starts.push(starts[starts.length - 1] + str.indexOf(" ") +1);
} else {
starts.push(1);
starts.push(str.indexOf(" ") +2);
//alert(str);
}
str = str.substring(str.indexOf(" ") + 1);
}
for (var i = 0; i < starts.length; i++) {
alert(starts[i] + ": " + orgStr.substring(starts[i]-1,starts[i]))
}
Easiest would be to search a regular expression \b\w and collect match.start() match.index for each match. Loop while there's matches.
EDIT: wrong language. lol.