Javascript Shortcode Parse - javascript

I need to parse following shortcode, for example my shortcode is :
[shortcode one=this two=is three=myshortcode]
I want to get this, is and myshortcode and add to array so it will :
['this', 'is', 'myshortcode']
NOTE : I know generally shortcode parameter marked with " and " ( ie [shortcode one="this" two="is" three="myshortcode"] ), but I need to parse shortcode above without ""
Any help really appreciated

I'm assuming you want to parse the first string with Regex and output the three elements in order to add them to an array later. That seems rather simple, or am I misunderstanding what you need? I'm assuming the word shortcodeis as it will be in your string. You'd probably need two regex operations if you haven't located and isolated the shortcode string yet that you posted above:
/\[shortcode((?: \S+=\S+)+)\]/
Replacement: "$1"
If you already have the code exactly as you posted it, then you can skip the regex above. At any rate, you'll have end with the following regex:
/ \S+=(\S+)(?:$| )/g
You can then add all the matches to your array.
If this is is not what you're looking for, then perhaps a more real example of your code would help.

Here you go I have built a perfectly scalable solution for you. The solution works for any number of parameters.
function myFunction() {
var str = "[shortcode one=this two=is three=myshortcode hello=sdfksj]";
var output = new Array();
var res = str.split("=");
for (i = 1; i < res.length; i++) {
var temp = res[i].split(" ");
if(i == res.length-1){
temp[0] = temp[0].substring(0,temp[0].length-1);
}
output.push(temp[0]);
}
document.getElementById("demo").innerHTML = output;
}
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

var str="[shortcode one=this two=is three=myshortcode]";
eval('var obj=' + str.replace(/shortcode /,"").replace(/=/g,"':'").replace(/\[/g,"{'").replace(/\]/g,"'}").replace(/ /g,"','"));
var a=[];
for(x in obj) a.push(obj[x]);
console.log(a);
You can try the above code.

Here's my solution: https://jsfiddle.net/t6rLv74u/
Firstly, remove the [shortcode and trailing ]
Next, split the result by space " "
After that, run through the array and remove anything that's on and before =, .*?=.
And now you have your result.

Related

Change occurrences of sum(something) to something_sum

Admittedly I'm terrible with RegEx and pattern replacements, so I'm wondering if anyone can help me out with this one as I've been trying now for a few hours and in the process of pulling my hair out.
Examples:
sum(Sales) needs to be converted to Sales_sum
max(Sales) needs to be converted to Sales_max
min(Revenue) needs to be converted to Revenue_min
The only available prefixed words will be sum, min, max, avg, xcount - not sure if this makes a difference in the solution.
Hopefully that's enough information to kind of show what I'm trying to do. Is this possible via RegEx?
Thanks in advance.
There are a few possible ways, for example :
var str = "min(Revenue)";
var arr = str.match(/([^(]+)\(([^)]+)/);
var result = arr[2]+'_'+arr[1];
result is then "Revenue_min".
Here's a more complex example following your comment, handling many matches and lowercasing the verb :
var str = "SUM(Sales) + MIN(Revenue)";
var result = str.replace(/\b([^()]+)\(([^()]+)\)/g, function(_,a,b){
return b+'_'+a.toLowerCase()
});
Result : "Sales_sum + Revenue_min"
Try with:
var input = 'sum(Sales)',
matches = input.match(/^([^(]*)\(([^)]*)/),
output = matches[2] + '_' + matches[1];
console.log(output); // Sales_sum
Also:
var input = 'sum(Sales)',
output = input.replace(/^([^(]*)\(([^)]*)\)/, '$2_$1');
You can use replace with tokens:
'sum(Sales)'.replace(/(\w+)\((\w+)\)/, '$2_$1')
Using a whitelist for your list of prefixed words:
output = input.replace(/\b(sum|min|max|avg|xcount)\((.*?)\)/gi,function(_,a,b) {
return b.toLowerCase()+"_"+a;
});
Added \b, a word boundary. This prevents something like "haxcount(xorz)" from becoming "haxorz_xcount"

How to use string.split( ) for the following string in javascript

I have the following string: (17.591257793993833, 78.88544082641602) in Javascript
How do I use split() for the above string so that I can get the numbers separately.
This is what I have tried (I know its wrong)
var location= "(17.591257793993833, 78.88544082641602)";
var sep= location.split("("" "," "")");
document.getElementById("TextBox1").value= sep[1];
document.getElementById("Textbox2").value=sep[2];
Suggestions please
Use regular expression, something as simple as following would work:
// returns and array with two elements: [17.591257793993833, 78.88544082641602]
"(17.591257793993833, 78.88544082641602)".match(/(\d+\.\d+)/g)
You could user Regular Expression. That would help you a lot. Together with the match function.
A possible Regexp for you might be:
/\d+.\d+/g
For more information you can start with wiki: http://en.wikipedia.org/wiki/Regular_expression
Use the regex [0-9]+\.[0-9]+. You can try the regex here.
In javascript you could do
var str = "(17.591257793993833, 78.88544082641602)";
str.match(/(\d+\.\d+)/g);
Check it.
If you want the values as numbers, i.e. typeof x == "number", you would have to use a regular expression to get the numbers out and then convert those Strings into Numbers, i.e.
var numsStrings = location.match(/(\d+.\d+)/g),
numbers = [],
i, len = numsStrings.length;
for (i = 0; i < len; i++) {
numbers.push(+numsStrings[i]);
}

javascript split with regex

I would like to split characters into array using javascript with regex
foo=foobar=&foobar1=foobar2=
into
foo, foobar=,
foobar1, foobar2=
Sorry for not being clear, let me re describe the scenario.
First i would split it by "&" and want to post process it later.
str=foo=foobar=&foobar1=foobar2=
var inputvars=str.split("&")
for(i=0;i<inputvars.length;i++){
var param = inputvars[i].split("=");
console.log(param);
}
returns
[foo,foobar]
[]
[foobar1=foobar2]
[]
I tried to use .split("=") but foobar= got splited out as foobar.
I essentially want it to be
[foo,foobar=]
[foobar1,foobar2=]
Any help with using javascript to split first occurence of = only?
/^([^=]*)=(.*)/.exec('foo=foobar=&foobar1=foobar2=')
or simpler to write but using the newer "lazy" operator:
/(.*?)=(.*)/.exec('foo=foobar=&foobar1=foobar2=')
from malvolio, i got to conclusion below
var str = 'foo=foobar=&foobar1=foobar2=';
var inputvars = str.split("&");
var pattern = /^([^=]*)=(.*)/;
for (counter=0; counter<inputvars.length; counter++){
var param = pattern.exec(inputvars[counter]);
console.log(param)
}
and results (which is what i intended)
[foo,foobar=]
[foobar1,foobar2=]
Thanks to #malvolio hint of regex
Cheers

javascript - replacing spaces with a string

I'm new to Javascript and need a bit of help with program on a college course to replace all the spaces in a string with the string "spaces".
I've used the following code but I just can't get it to work:
<html>
<body>
<script type ="text/javascript">
// Program to replace any spaces in a string of text with the word "spaces".
var str = "Visit Micro soft!";
var result = "";
For (var index = 0; index < str.length ; index = index + 1)
{
if (str.charAt(index)= " ")
{
result = result + "space";
}
else
{
result = result + (str.charAt(index));
}
}
document.write(" The answer is " + result );
</script>
</body>
</html>
For
isn't capitalized:
for
and
str.charAt(index)= " "
needs to be:
str.charAt(index) == " "
JavaScript Comparison Operators
for loops
As others have mentioned there are a few obvious errors in your code:
The control flow keyword for must be all lower-case.
The assignment operator = is different than the comparison operators == and ===.
If you are allowed to use library functions then this problem looks like a good fit for the JavaScript String.replace(regex,str) function.
Another option would be to skip the for cycle altogether and use a regular expression:
"Visit Micro soft!".replace(/(\s)/g, '');
Try this:
str.replace(/(\s)/g, "spaces")
Or take a look at this previous answer to a similar question: Fastest method to replace all instances of a character in a string Hope this help
You should use the string replace method. Inconvenienty, there is no replaceAll, but you can replace all anyways using a loop.
Example of replace:
var word = "Hello"
word = word.replace('e', 'r')
alert(word) //word = "Hrllo"
The second tool that will be useful to you is indexOf, which tells you where a string occurs in a string. It returns -1 if the string does not appear.
Example:
var sentence = "StackOverflow is helpful"
alert(sentence.indexOf(' ')) //alerts 13
alert(sentence.indexOf('z')) //alerts -1

Remove everything after a certain character

Is there a way to remove everything after a certain character or just choose everything up to that character? I'm getting the value from an href and up to the "?", and it's always going to be a different amount of characters.
Like this
/Controller/Action?id=11112&value=4444
I want the href to be /Controller/Action only, so I want to remove everything after the "?".
I'm using this now:
$('.Delete').click(function (e) {
e.preventDefault();
var id = $(this).parents('tr:first').attr('id');
var url = $(this).attr('href');
console.log(url);
}
You can also use the split() function. This seems to be the easiest one that comes to my mind :).
url.split('?')[0]
jsFiddle Demo
One advantage is this method will work even if there is no ? in the string - it will return the whole string.
var s = '/Controller/Action?id=11112&value=4444';
s = s.substring(0, s.indexOf('?'));
document.write(s);
Sample here
I should also mention that native string functions are much faster than regular expressions, which should only really be used when necessary (this isn't one of those cases).
Updated code to account for no '?':
var s = '/Controller/Action';
var n = s.indexOf('?');
s = s.substring(0, n != -1 ? n : s.length);
document.write(s);
Sample here
var href = "/Controller/Action?id=11112&value=4444";
href = href.replace(/\?.*/,'');
href ; //# => /Controller/Action
This will work if it finds a '?' and if it doesn't
May be very late party :p
You can use a back reference $'
$' - Inserts the portion of the string that follows the matched substring.
let str = "/Controller/Action?id=11112&value=4444"
let output = str.replace(/\?.*/g,"$'")
console.log(output)
It works for me very nicely:
var x = '/Controller/Action?id=11112&value=4444';
var remove_after= x.indexOf('?');
var result = x.substring(0, remove_after);
alert(result);
If you also want to keep "?" and just remove everything after that particular character, you can do:
var str = "/Controller/Action?id=11112&value=4444",
stripped = str.substring(0, str.indexOf('?') + '?'.length);
// output: /Controller/Action?
You can also use the split() method which, to me, is the easiest method for achieving this goal.
For example:
let dummyString ="Hello Javascript: This is dummy string"
dummyString = dummyString.split(':')[0]
console.log(dummyString)
// Returns "Hello Javascript"
Source: https://thispointer.com/javascript-remove-everything-after-a-certain-character/
if you add some json syringified objects, then you need to trim the spaces too... so i add the trim() too.
let x = "/Controller/Action?id=11112&value=4444";
let result = x.trim().substring(0, x.trim().indexOf('?'));
Worked for me:
var first = regexLabelOut.replace(/,.*/g, "");
It can easly be done using JavaScript for reference see link
JS String
EDIT
it can easly done as. ;)
var url="/Controller/Action?id=11112&value=4444 ";
var parameter_Start_index=url.indexOf('?');
var action_URL = url.substring(0, parameter_Start_index);
alert('action_URL : '+action_URL);

Categories