I have a url with many delimiters '/'.
I want to find the string after the last delimiter. How can I write a javascript code?
for eg if my url is
localhost/sample/message/invitation/create/email
I want to display 'email' as my output.
var last = input.split("/").pop();
Simples!
Splitting on a regex that matches spaces or hyphens and taking the last element
var lw = function(v) {
return (""+v).replace(/[\s-]+$/,'').split(/[\s-]/).pop();
};
lw('This is a test.'); // returns 'test.'
lw('localhost/sample/message/invitation/create/email,'); // returns 'email,'
var url="localhost/sample/message/invitation/create/email";
url.split("/").pop()
or
var last=$(url.split("/")).last();
Usng simple regex
var str = "localhost/sample/message/invitation/create/email";
var last = str.match(/[^/]*$/)[0]";
Above regex return all character after last "/"
Related
Working with Javascript I need to be able to search a string input from a user and replace occurrences of semicolons with commas. Issue I have ran into is I need to be able to search the string for any commas that already exist, and quote around to the last and next occurrence of the semicolon.
Example:
User input is 12345;Joran,Michael;02;17;63 it should be converted to 12345,"Joran,Michael",02,17,63
My includes is able to locate the occurrence of a comma in the original string var srch = source.includes(","); and my replace is var converted = source.replace(/;/g, ","); which works fine, just need to figure out how to get to the last/next semicolon to place the quotes.
Using an if/else depending on if srch evaluates to True -- if true, add the quotes and then convert the rest of the string and return to the user; if false, convert and return.
I'm sure there's a way to do this with regex that just hasn't came to me yet so any suggestions on what to look at would be great.
I'd do this in two steps. First match non-; characters which have at least one ,, and surround them with quotes. Then replace all ;s in the result with ,:
console.log(
'12345;Joran,Michael;02;17;63'
.replace(/[^;,]*,[^;]*/g, '"$&"')
.replace(/;/g, ',')
);
Split the string by ;
.split(';')
which gives you an array.
Convert the elements that include a ',' to "${element}"
.map(s => s.includes(',') ? `"${s}"` : s )
Convert the array back to string
.join(',')
var str = '12345;Joran,Michael;02;17;63';
var arr = str.split(";");
var letters = /^[A-Za-z]/;
var final_str = "";
for (var i = 0; i < arr.length; i++) {
final_str = arr[i].match(letters)?final_str +'"'+ arr[i]+'"'+",":final_str + arr[i]+",";
}
console.log(final_str.substring(0,final_str.length -1));
Suppose I have a sting like this: ABC5DEF/G or it might be ABC5DEF-15 or even just ABC5DEF, it could be shorter AB7F, or AB7FG/H.
I need to create a javascript variable that contains the substring only up to the '/' or the '-'. I would really like to use an array of values to break at. I thought maybe to try something like this.
...
var srcMark = array( '/', '-' );
var whereAt = new RegExp(srcMark.join('|')).test.str;
alert("whereAt= "+whereAt);
...
But this returns an error: ReferenceError: Can't find variable: array
I suspect I'm defining my array incorrectly but trying a number of other things I've been no more successful.
What am I doing wrong?
Arrays aren't defined like that in JavaScript, the easiest way to define it would be with:
var srcMark = ['/','-'];
Additionally, test is a function so it must be called as such:
whereAt = new RegExp(srcMark.join('|')).test(str);
Note that test won't actually tell you where, as your variable suggests, it will return true or false. If you want to find where the character is, use String.prototype.search:
str.search(new RegExp(srcMark.join('|'));
Hope that helps.
You need to use the split method:
var srcMark = Array.join(['-','/'],'|'); // "-|/" or
var regEx = new RegExp(srcMark,'g'); // /-|\//g
var substring = "222-22".split(regEx)[0] // "222"
"ABC5DEF/G".split(regEx)[0] // "ABC5DEF"
From whatever i could understand from your question, using this RegExp /[/-]/ in split() function will work.
EDIT:
For splitting the string at all special characters you can use new RegExp(/[^a-zA-Z0-9]/) in split() function.
var arr = "ABC5DEF/G";
var ans = arr.split(/[/-]/);
console.log(ans[0]);
arr = "ABC5DEF-15";
ans = arr.split(/[/-]/);
console.log(ans[0]);
// For all special characters
arr = "AB7FG/H";
ans = arr.split(new RegExp(/[^a-zA-Z0-9]/));
console.log(ans[0]);
You can use regex with String.split.
It will look something like that:
var result = ['ABC5DEF/G',
'ABC5DEF-15',
'ABC5DEF',
'AB7F',
'AB7FG/H'
].map((item) => item.split(/\W+/));
console.log(result);
That will create an Array with all the parts of the string, so each item[0] will contain the text till the / or - or nothing.
If you want the position of the special character (non-alpha-numeric) you can use a Regular Expression that matches any character that is not a word character from the basic Latin alphabet. Equivalent to [^A-Za-z0-9_], that is: \W
var pattern = /\W/;
var text = 'ABC5DEF/G';
var match = pattern.exec(text);
var position = match.index;
console.log('character: ', match[0]);
console.log('position: ', position);
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 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.