I can’t quite figure out the best way to do this but I have a series of values that are being fed into my jquery plugin. I’m following the convention of adding a space after each value. I then grab the jquery parameters and attempt to add a ‘,’ to each one so that it can be feed into a json call. The problem is that if I add a ‘,’ in place of the space and the value returned from the variable in the plugin is empty I get multiple commas that I don’t need. (i.e. ,,podcast). How would I only add a comma if there is a value in my variable?
$(document).ready(function () {
$('#gallery').mediaFilters({
mediaType: '${article} ${podcast} ${image}',
headerType: '${internet} ${cloud} ${background}',
});
});
JQUERY to send to JSON:
var mediaType = "&mediaType=" + opts.mediaType.split(/[ ]/).join(',');
var headerType = "&headerType=" + opts.headerType.split(/[ ]/).join(',');
The regex / +/ will match multiple spaces, so the input a b will turn into a,b.
The regex /^ *| *$/ will match the spaces at the beginning and end of the string.
Together, here is code that will replace those with a comma, and remove the beginning and end spaces.
var mediaType = "&mediaType=" + opts.mediaType.replace(/^ *| *$/g,'').replace(/ +/g,',');
var headerType = "&headerType=" + opts.headerType.replace(/^ *| *$/g,'').replace(/ +/g,',');
Related
I have a stringified JSON which looks like this:
...
"message":null,"elementId:["xyz1","l9ie","xyz1"]}}]}], "startIndex":"1",
"transitionTime":"3","sourceId":"xyz1","isLocked":false,"autoplay":false
,"mutevideo":false,"loopvideo":false,"soundonhover":false,"videoCntrlVisibility":0,
...,"elementId:["dgff","xyz1","jkh90"]}}]}]
... it goes on.
The part I need to work on is the value of the elementId key. (The 2nd key in the first line, and the last key).
This key is present in multiple places in the JSON string. The value of this key is an array containing 4-character ids.
I need to replace one of these ids with a new one.
The kernel of the idea is something like:
var elemId = 'xyz1' // for instance
var regex = new RegExp(elemId, 'g');
var newString = jsonString.replace(regex, newRandomId);
jsonString = newString;
There are a couple of problems with this approach. The regex will match the id anywhere in the JSON. I need a regex which only matches it inside the elementId array; and nowhere else.
I'm trying to use a capturing group to match just the occurrences I need, but I can't quite crack it. I have:
/.*elementId":\[".*(xyz1).*"\]}}]/
But this doesn't match the 1st occurence of 'xyz1 in the array.
So, firstly, I need a regex which can match all the 'xyz1's inside elementId; but nowhere else. The sequence of square and curly brackets after elementId ends doesn't change anywhere in the string, if that helps.
Secondly, even if I have a capturing group that works, string.replace doesn't act as expected. Instead of replacing just the match inside the capturing group, it replaces the whole match.
So, my second requirement is replacing only the captured groups, not the whole match.
What a need is a piece of js code which will replace my 'xyz1's where needed and return the following string (assuming the newRandomId is 'abcd'):
"message":null,"elementId:["abcd","l9ie","abcd"]}}]}], "startIndex":"1",
"transitionTime":"3","sourceId":"xyz1","isLocked":false,"autoplay":false
,"mutevideo":false,"loopvideo":false,"soundonhover":false,"videoCntrlVisibility":0,
...,"elementId:["dgff","abcd","jkh9"]}}]}]
Note that the value of 'sourceId' is unaffected.
EDIT: I have to work with the JSON. I can't parse it and work with the object since I don't know all the places the old id might be in the object and looping through it multiple times (for multiple elements) would be time-consuming
Assuming you can't just parse and change the JS object, you could use 2 regexes: one to extract the array and the one to change the desired ids inside:
var output = input.replace(/("elementId"\s*:\s*\[)((?:".{4}",?)*)(\])/g, function(_,start,content,end){
return start + content.replace(/"xyz1"/g, '"rand"') + end;
});
The arguments _, start, content, end are produced as result of the regex (documentation here):
_ is the whole matched string (from "elementId:\[ to ]). I choose this name because it's an old convention for arguments you don't use
start is the first group ("elementId:\[)
content is the second captured group, that is the internal part of the array
end id the third group, ]
Using the groups instead of hardcoding the start and end parts in the returned string serves two purposes
avoid duplication (DRY principle)
make it possible to have variable strings (for example in my regex I accept optional spaces after the :)
var input = document.getElementById("input").innerHTML.trim();
var output = input.replace(/("elementId":\s*\[)((?:".{4}",?)*)(\])/g, function(_,start,content,end){
return start + content.replace(/"xyz1"/g, '"rand"') + end;
});
document.getElementById("output").innerHTML = output;
Input:
<pre id=input>
"message":null,"elementId":["xyz1","l9ie","xyz1"]}}]}], "startIndex":"1",
"transitionTime":"3","sourceId":"xyz1","isLocked":false,"autoplay":false
,"mutevideo":false,"loopvideo":false,"soundonhover":false,"videoCntrlVisibility":0,
...,"elementId":["dgff","xyz1","jkh9"]}}]}]
</pre>
Output:
<pre id=output>
</pre>
Notes:
it would be easy to do the whole operation in one regex if they weren't repetition of the searched id in one array. But the present structure makes it easy to handle several ids to replace at once.
I use non captured groups (?:...) in order to unclutter the arguments passed to the external replacing callback
I have an RTF string that contains \*\revtbl{Unknown;}}, it is used to indecate that the word that follows is misspelled (I think) and I need to remove it, when I do:
.replace(/{\*\revtbl{Unknown;}}/g, "")
I get two lines:
*
evtbl{Unknown;}}
When I change to:
.replace(/{\*\r|evtbl{Unknown;}}/g, "")
I get just the * and a second line. e.g.:
var tt = '\*\revtbl{Unknown;}}';
tt=tt.replace(/{\*\r|evtbl{Unknown;}}/g, "");
alert('"'+tt+'"');
I see:
"*
"
I could not find any reference about the use of the pipe | character so I need to know: if by using it am I asking to replace two separate strings one being {\*\r and the other being evtbl{Unknown;}} bottom line I need to replace the literal string \*\revtbl{Unknown;}} with nothing.
I think it is just a matter of escaping all the characters correctly
//sample string - NOTE: the backslashes had to be escaped for JS
var str = "RTF string that contains \\*\\revtbl{Unknown;}}, it is used to indecate that the word that follows is misspelled (I think) and I need to remove it, when I do:";
var regEx = /\\\*\\revtbl\{Unknown;\}\}/g;
console.log(str.replace(regEx, ''));
In an html template I get a variable's value from a select drop down list like
one or more,two
In need to add an extra space after the comma and I need my string to be
one or more, two
My current javascript is:
$('#id_diag-diagnosis_option').change(function () {
var value = $(this).val()
alert(value)
Do you have any idea?
value.replace(/\s/g, '').split(",").join(", ")
should work for all cases (anything other than one space after comma)
var after = before.replace(",", ", ");
Should work (Before being the string before the change, and after being after)
I have one string as
str="NA,No Therapis delivered,No Therapies Available,None,ATP,CVRT,CVRT x 2,No VT Available,Aborted CVRT,Aborted Defib,Defib,Defib(DBT)"
I want a regular expression that would match comma seperated values.
I am using Datatable to show above string in a table.
e.g If i enter 'cvrt' then only 'cvrt' from above strin should be returned.
If I enter 'No Therapis delivered' then only 'No Therapis delivered' should be return.
As I want to do Datatable search, split() method wont work for me.
Only option is to use regular expression.
Thanks in Advance
You could try something like so: (^|,)No Therapies Available(,|$). This will look for a particular word, in the case, No Therapies Available which is preceded by either by the beginning of the string (^) or a comma (,) and is succeeded either by another comma (,) or the end of the string ($).
As per this previous SO question, you could use exec to match and obtain the location of your search results.
EDIT: The code would look something like so:
var searchText = ...;
var searchableText = ...;
var match = [];
var regex = "(^|,)(" + searchText + ")(,|$)/g"
while(match = regex.exec(searchableText)) != null)
{
alert("Item found at " + match[1].index);
}
EDIT 2:
The comma's will be part of the match since those are part of the pattern. My updated answer uses groups to go round this problem, which it would seem is not something you have access to. To go round this problem, you could do something like so:
var matchedText = $('#example').dataTable().fnFilter( "(^|,)" + searchText + "(,|$)/g",columnIndex,true); //this should return a string of the form ',foobar,`
//We then proceed to clean the string by removing leading/trailing commas:
matchedText = matchedText.replace("^,", ""); //Remove leading commas.
matchedText = matchedText.replace(",$", ""); //Remove trailing commas.
alert("Matched Text: " + matchedText);
How I can get the value after last char(. ; + _ etc.):
e.g.
string.name+org.com
I want to get "com".
Is there any function in jQuery?
Use lastIndexOf and substr to find the character and get the part of the string after it:
var extension = name.substr(name.lastIndexOf(".") + 1);
Demo: http://jsfiddle.net/Guffa/K3BWn/
A simple and readable approch to get the substring after the last occurrence of a character from a defined set is to split the string with a regular expression containing a character class and then use pop() to get the last element of the resulting array:
The pop() method removes the last element from an array and returns that element.
See a JS demo below:
var s = 'string.name+org.com';
var result = s.split(/[.;+_]/).pop();
console.log(result);
to split at all non-overlapping occurrences of the regex by default.
NOTE: If you need to match ^, ], \ or -, you may escape them and use anywhere inside the character class (e.g. /[\^\-\]\\]/). It is possible to avoid escaping ^ (if you do not put it right after the opening [), - (if it is right after the opening [, right before the closing ], after a valid range, or between a shorthand character class and another symbol): /[-^\]\\]/.
Also, if you need to split with a single char, no regex is necessary:
// Get the substring after the last dot
var result = 'string.name+org.com'.split('.').pop();
console.log(result);
Not jQuery, just JavaScript: lastIndexOf and substring would do it (not since the update indicating multiple characters). As would a regular expression with a capture group containing a character class followed by an end-of-string anchor, e.g. /([^.;+_]+)$/ used with RegExp#exec or String#match.
E.g. (live copy | source):
var match = /([^.;+_]+)$/.exec(theStringToTest),
result = match && match[1];
var s = "string.name+org.com",
lw = s.replace(/^.+[\W]/, '');
console.log(lw) /* com */
this will also work for
string.name+org/com
string.name+org.info
You can use RegExp Object.
Try this code:
"http://stackoverflow.com".replace(/.*\./,"");
I'll throw in a crazy (i.e. no RegExp) one:
var s = 'string.name+org.com';
var a = s.split('.'); //puts all sub-Strings delimited by . into an Array
var result = a[a.length-1]; //gets the last element of that Array
alert(result);
EDIT: Since the update of the question is demanding mutiple delimiters to work this is probably not the way to go. Too crazy.....
use javascript function like
url.substr(url.length - 3);
maybe this is too late to consider, this codes works fine for me using jquery
var afterDot = value.substr(value.lastIndexOf('_') + 1);
You could just replate '_' to '.'
var myString = 'asd/f/df/xc/asd/test.jpg'
var parts = myString.split('/');
var answer = parts[parts.length - 1];
console.log(answer);