I have such a structure "\"item:Test:3:Facebook\"" and I need somehow fetch the word Facebook.
The words can be dynamic. So I need to get word which is after third : and before \
I tried var arr = str.split(":").map(item => item.trim()) but it doesn't do what I need. How can I cut a word that will be after third : ?
A litte extra code to remove the last " aswell.
var str = "\":Test:3:Facebook\"";
var arr = str.split(":").map(item => item.trim());
var thirdItem = arr[3].replace(/[^a-zA-Z]/g, "");
console.log(thirdItem);
If the amount of colons (:) doesn't vary you can simply use an index on the resulting array like this:
var foo = str.split(":")[3];
The word after the 3rd : will be the fourth word returned, so it will be at index 3 in the array returned by split() (arrays being zero-indexed, of course). You might also want to get rid of the trailing quote mark.
Demo:
str = "\"item:Test:3:Facebook\"";
var word = str.split(":")[3].replace("\"", "");
console.log(word);
This should do the trick, plus remove all symbols
var foo = str.split(":")[3].replace(/[^a-zA-Z ]/g, "")
Related
I want to do this in node.js
example.js
var str = "a#universe.dev";
var n = str.includes("b#universe.dev");
console.log(n);
but with restriction, so it can search for that string only after the character in this example # so if the new search string would be c#universe.dev it would still find it as the same string and outputs true because it's same "domain" and what's before the character in this example everything before # would be ignored.
Hope someone can help, please
Look into String.prototype.endsWith: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
First, you need to get the end of the first string.
var ending = "#" + str.split("#").reverse()[0];
I split your string by the # character, so that something like "abc#def#ghi" becomes the array ["abc", "def", "ghi"]. I get the last match by reversing the array and grabbing the first element, but there are multiple ways of doing this. I add the separator character back to the beginning.
Then, check whether your new string ends the same:
var n = str.endsWith(ending);
console.log(n);
var str = "a#universe.dev";
var str2 = 'c#universe.dev';
str = str.split('#');
str2 = str2.split('#');
console.log(str[1] ===str2[1]);
With split you can split string based on the # character. and then check for the element on position 1, which will always be the string after #.
Declare the function
function stringIncludeAfterCharacter(s1, s2, c) {
return s1.substr(s1.indexOf(c)) === s2.substr(s2.indexOf(c));
}
then use it
console.log(stringIncludeAfterCharacter('a#universe.dev', 'b#universe.dev', '#' ));
var str = "a#universe.dev";
var n = str.includes(str.split('#')[1]);
console.log(n);
Another way !
var str = "a#universe.dev";
var n = str.indexOf(("b#universe.dev").split('#')[1]) > -1;
console.log(n);
I have got of array symbols as shown below
var sourcesymbols = ["ERT", "UBL" , "AMAZING"];
I am getting the following news title from rss feed
you experts are amazing
How to check if the content present in the rssfeedstring is present under the sourcesymbols array or not ??
For example rssfeedstring has word amazing and it is also present under sourcesymbols
please let me know how to achive this .
I have tried to convert the rssfeedstring to uppercase then i am not sure how to use the indexOf on the string .
rssfeedstring = rssfeedstring.toUpperCase();
please let em know if there is any better approach also for doing this as the array will have 2000 symbols
http://jsfiddle.net/955pfz01/3/
You can use regex.
Steps:
Convert the array to string with join using |(OR in regex) as glue
Use \b-word boundary to match exact words
Use i flag on regex to match irrespective of the case. So, don't have to change the case of string.
Escape the slashes as using RegExp constructor requires string to be passed and \ in string is used as escape following character.
test can be used on regex to check if the string passes the regex.
var sourcesymbols = ["ERT", "UBL", "AMAZING"];
var mystr = 'you experts are amazing';
var regex = new RegExp("\\b(" + sourcesymbols.join('|') + ")\\b", 'i'); // /\b(ERT|UBL|AMAZING)\b/i
alert(regex.test(mystr));
You can also use some
Convert the string to array by using split with \s+. This will split the string by any(spaces, tabs, etc) one or more space character
Use some on splitted array
Convert the string to uppercase for comparing
Check if the element is present in array using indexOf
var mystr = 'you experts are amazing';
var sourcesymbols = ["ERT", "UBL", "AMAZING"];
var present = mystr.toUpperCase().split(/\s+/).some(function(e) {
return sourcesymbols.indexOf(e) > -1;
});
alert(present);
Try using Array.prototype.map() , Array.prototype.indexOf() to return matched text, index of matched text within sourcesymbols
var sourcesymbols = ["ERT", "UBL" , "AMAZING"];
var mystr = 'you experts are amazing';
var res = mystr.split(" ").map(function(val, index) {
var str = val.toUpperCase(), i = sourcesymbols.indexOf(str);
return i !== -1 ? [val, i] : null
}).filter(Boolean);
console.log(res)
jsfiddle http://jsfiddle.net/955pfz01/6/
I am trying to remove some spaces from a few dynamically generated strings. Which space I remove depends on the length of the string. The strings change all the time so in order to know how many spaces there are, I iterate over the string and increment a variable every time the iteration encounters a space. I can already remove all of a specific type of character with str.replace(' ',''); where 'str' is the name of my string, but I only need to remove a specific occurrence of a space, not all the spaces. So let's say my string is
var str = "Hello, this is a test.";
How can I remove ONLY the space after the word "is"? (Assuming that the next string will be different so I can't just write str.replace('is ','is'); because the word "is" might not be in the next string).
I checked documentation on .replace, but there are no other parameters that it accepts so I can't tell it just to replace the nth instance of a space.
If you want to go by indexes of the spaces:
var str = 'Hello, this is a test.';
function replace(str, indexes){
return str.split(' ').reduce(function(prev, curr, i){
var separator = ~indexes.indexOf(i) ? '' : ' ';
return prev + separator + curr;
});
}
console.log(replace(str, [2,3]));
http://jsfiddle.net/96Lvpcew/1/
As it is easy for you to get the index of the space (as you are iterating over the string) , you can create a new string without the space by doing:
str = str.substr(0, index)+ str.substr(index);
where index is the index of the space you want to remove.
I came up with this for unknown indices
function removeNthSpace(str, n) {
var spacelessArray = str.split(' ');
return spacelessArray
.slice(0, n - 1) // left prefix part may be '', saves spaces
.concat([spacelessArray.slice(n - 1, n + 1).join('')]) // middle part: the one without the space
.concat(spacelessArray.slice(n + 1)).join(' '); // right part, saves spaces
}
Do you know which space you want to remove because of word count or chars count?
If char count, you can Rafaels Cardoso's answer,
If word count you can split them with space and join however you want:
var wordArray = str.split(" ");
var newStr = "";
wordIndex = 3; // or whatever you want
for (i; i<wordArray.length; i++) {
newStr+=wordArray[i];
if (i!=wordIndex) {
newStr+=' ';
}
}
I think your best bet is to split the string into an array based on placement of spaces in the string, splice off the space you don't want, and rejoin the array into a string.
Check this out:
var x = "Hello, this is a test.";
var n = 3; // we want to remove the third space
var arr = x.split(/([ ])/); // copy to an array based on space placement
// arr: ["Hello,"," ","this"," ","is"," ","a"," ","test."]
arr.splice(n*2-1,1); // Remove the third space
x = arr.join("");
alert(x); // "Hello, this isa test."
Further Notes
The first thing to note is that str.replace(' ',''); will actually only replace the first instance of a space character. String.replace() also accepts a regular expression as the first parameter, which you'll want to use for more complex replacements.
To actually replace all spaces in the string, you could do str.replace(/ /g,""); and to replace all whitespace (including spaces, tabs, and newlines), you could do str.replace(/\s/g,"");
To fiddle around with different regular expressions and see what they mean, I recommend using http://www.regexr.com
A lot of the functions on the JavaScript String object that seem to take strings as parameters can also take regular expressions, including .split() and .search().
I have to split the values using JavaScript and want to find the last occuring slash / from a string and replace the contents after the last slash / For example:
var word = "www.abc/def/ghf/ijk/**default.aspx**";
should become
var word ="www.abc/def/ghf/ijk/**replacement**";
The number of slashes may vary each time.
Try using regexp:
"www.abc/def/ghf/ijk/default.aspx".replace(/\/[^\/]+$/, "/replacement");
An alternative without regular expression (I just remembered lastIndexOf() method)
var word = "www.abc/def/ghf/ijk/default.aspx";
word = word.substring(0, word.lastIndexOf("/")) + "/replacement";
You can array split on '/', then pop the last element off the array, and rejoin.
word = word.split('/');
word.pop();
word = word.join('/') + replacement;
How about the KISS principle?
var word = "www.abc/def/ghf/ijk/default.aspx";
word = word.substring(0, word.lastIndexOf("/")) + "/replacement";
What about using a combination of the join() and split() functions?
var word = "www.abc/def/ghf/ijk/default.aspx";
// split the word using a `/` as a delimiter
wordParts = word.split('/');
// replace the last element of the array
wordParts[wordParts.length-1] = 'replacement';
// join the array back to a string.
var finalWord = wordParts.join('/');
The number of slashes doesn't matter here because all that is done is to split the string at every instance of the delimiter (in this case a slash).
Here is a working demo
Use regexp or arrays, something like:
[].splice.call(word = word.split('/'), -1, 1, 'replacement');
word = word.join('/');
I'm trying to split a string into an array based on the second occurrence of the symbol _
var string = "this_is_my_string";
I want to split the string after the second underscore. The string is not always the same but it always has 2 or more underscores in it. I always need it split on the second underscore.
In the example string above I would need it to be split like this.
var split = [this_is, _my_string];
var string = "this_is_my_string";
var firstUnderscore = string.indexOf('_');
var secondUnderscore = string.indexOf('_', firstUnderscore + 1);
var split = [string.substring(0, secondUnderscore),
string.substring(secondUnderscore)];
Paste it into your browser's console to try it out. No need for a jsFiddle.
var string = "this_is_my_string";
var splitChar = string.indexOf('_', string.indexOf('_') + 1);
var result = [string.substring(0, splitChar),
string.substring(splitChar, string.length)];
This should work.
var str = "this_is_my_string";
var matches = str.match(/(.*?_.*?)(_.*)/); // MAGIC HAPPENS HERE
var firstPart = matches[1]; // this_is
var secondPart = matches[2]; // _my_string
This uses regular expressions to find the first two underscores, and captures the part up to it and the part after it. The first subexpression, (.*?_.*?), says "any number of characters, an underscore, and again any number of characters, keeping the number of characters matched as small as possible, and capture it". The second one, (_.*) means "match an underscore, then any number of characters, as much of them as possible, and capture it". The result of the match function is an array starting with the full matched region, followed by the two captured groups.
I know this post is quite old... but couldn't help but notice that no one provided a working solution. Here's one that works:
String str = "this_is_my_string";
String undScore1 = str.split("_")[0];
String undScore2 = str.split("_")[1];
String bothUndScores = undScore1 + "_" + undScore2 + "_";
String allElse = str.split(bothUndScores)[1];
System.out.println(allElse);
This is assuming you know there will always be at least 2 underscores - "allElse" returns everything after the second occurrence.