I need a algorithm which is doing something like this:
var example = "Hello $$user$$ your real name is $$realname$$. Have a good day"
Output --> ["Hello ", "$$user$$", " your real name is ", "$$realname$$", ". Have a good day"]
Hence, split the part by a selected character and put them together in a string array. Can someone help me out?
I'm looking for a solution with JavaScript/jQuery
It seems you want to split by pattern $$...$$; You could use /(\$\$.*?\$\$)/; To keep the pattern in the result, you can make it a capture group, and also make it lazy (?) so that it will split with the shortest length pattern matched:
example.split(/(\$\$.*?\$\$)/)
#[ 'Hello ',
# '$$user$$',
# ' your real name is ',
# '$$realname$$',
# '. Have a good day' ]
Yes, this is possible with JavaScript itself... Slightly tricky, but yes.
var strings = [], tokens = [];
var str = "Hello $$user$$ your real name is $$realname$$. Have a good day".replace(/\$\$(.*?)\$\$/g, "\$\$TOKEN$1\$\$").split("$");
for (var i = 0; i < str.length; i++) {
if (str[i].indexOf("TOKEN") === 0) {
// This is a token.
tokens.push(str[i].replace("TOKEN", ""));
} else {
strings.push(str[i]);
}
}
str = str.map(function (v) {
if (v.indexOf("TOKEN") === 0)
return "$$" + v.replace("TOKEN", "") + "$$";
return v;
});
console.log(str);
console.log(strings);
console.log(tokens);
The above code will split everything into tokens. And on top of it, it also separates the strings and tokens out. The above one gives as per your requirement:
[
"Hello ",
"$$user$$",
" your real name is ",
"$$realname$$",
". Have a good day"
]
Kindly note, there's nothing like {value, value}, there's only [value, value].
String.split()
The split() method splits a String object into an array of strings by separating the string into substrings.
var example = "Hello $$user$$ your real name is $$realname$$. Have a good day";
var exSplit = example.split("$$");
var userIdx = exSplit.indexOf("user");
var nameIdx = exSplit.indexOf("realname");
document.querySelector(".user").innerHTML = exSplit[userIdx];
document.querySelector(".name").innerHTML = exSplit[nameIdx];
<div class="user"></div>
<div class="name"></div>
Though, if I may suggest, variables can handle this type of operation without all of the hassle.
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.
I am trying to replace all double commas with ,null,
The problem is that i need to keep doing it while it is replacing it. I am thinking about adding a loop but is there any other more eficient alternative?
var test = "[1,2,,,3,4,,,,,,5,6]".replace(/,{2}/g, ",null,");
alert(test);
The result should be:
"[1,2,null,null,3,4,null,null,null,null,null,5,6]"
But is instead:
[1,2,null,,3,4,null,,null,,null,5,6]
So I would have to create a loop and do it until all double commas are done. Not sure if there is any other way?
As a side info, this is so that I can afterwards do:
var myArray = $.parseJSON(test);
Which currently it fails which I'm guessing that it's because it is not valid json.
Single regex:
"[AB,,,CD,,,,,,EF]".replace(/,(?=,)/g, ',null');
demo
Here we use the ?= lookahead to find 2 commas ("comma with a comma after it") but match and replace only the first.
Edit:
You seem to be interested in speed, here are some tests.
str.split(',').map(function(x) { return x ? x : 'null' }).join(',');
FIDDLE
splits the string by commas, then map() iterates and returns each value from the callback, and the ternary returns x (the value) if thruthy and the string 'null' if falsy, which an empty string is, then join it back together again.
You can do this:
var test = "[1,2,,,3,4,,,,,,5,6]".split(',').join(',|').replace(/\|,/g,"null,");
alert(test.replace(/\|/g,""));
It alerts:
[1,2,null,null,3,4,null,null,null,null,null,5,6]
Demo: http://jsfiddle.net/AmitJoki/Zuv38/
Not sure if regex could handle that without looping.
Alternative solution is to split is into an array: '1,2,,,3,4,,,,,,5,6'.split(','); and then loop through it and replace all empty strings with null and then join it back.
So, something like this:
var s = '1,2,,,3,4,,,,,,5,6';
var a = s.split(',');
for (var i = 0; i < a.length; i++) {
if (a[i] == "") {
a[i] = "null";
}
}
s = '[' + a.join(',') + ']';
See it here: http://jsfiddle.net/fVMLv/1/
Try this
var str = "1,2,,,3,4,,,,,,5,6";
str = str.split(',');
var strResult ='';
$(str).each(function(){
if(this==''){
strResult +='null,';
}
else{
strResult +=this+',';
}
});
strResult = strResult.substring(0,strResult.length-1);
alert(strResult);
DEMO
The problem is with the double commas occurring consecutively.
,,,, -> will be taken as 2 sets of double commas by that RegExp. So, result will be:-
,null,,null, -> note that the occurrence of another double comma in between is skipped, since the RegEx is greedy (2nd comma is already used, which is not used again together with 3rd comma. rather 3rd and 4th are used together).
var test = "[AB,,,CD,,,,,,EF]".replace(/,,/g, ",null,").replace(/,,/g, ",null,");
alert(test);
So, with this RegExp, calling it twice will fix this.
I have a string like
:21::22::24::99:
And I want to find say if :22: is in said string. But is there a means of searching a string like above for one like I want to match it to with javascript, and if there is, does it involve regex magic or is there something else? Either way not sure how to do it, more so if regex is involved.
You can build the regular expression you need:
function findNumberInString(num, s) {
var re = new RegExp(':' + num + ':');
return re.test(s);
}
var s = ':21::22::24::99';
var n = '22';
findNumberInString(n, s); // true
or just use match (though test is cleaner to me)
!!s.match(':' + n + ':'); // true
Edit
Both the above use regular expressions, so a decimal ponit (.) will come to represent any character, so "4.1" will match "461" or even "4z1", so better to use a method based on String.prototype.indexOf just in case (unless you want "." to represent any character), so per Blender's comment:
function findNumberInString(num, s) {
return s.indexOf(':' + num + ':') != -1;
}
like this:
aStr = ':21::22::24::99:';
if(aStr.indexOf(':22:') != -1){
//':22:' exists in aStr
}
else{
//it doesn't
}
I have a paragraph that's broken up into an array, split at the periods. I'd like to perform a regex on index[i], replacing it's contents with one instance of each letter that index[i]'s string value has.
So; index[i]:"This is a sentence" would return --> index[i]:"thisaenc"
I read this thread. But i'm not sure if that's what i'm looking for.
Not sure how to do this in regex, but here's a very simple function to do it without using regex:
function charsInString(input) {
var output='';
for(var pos=0; pos<input.length; pos++) {
char=input.charAt(pos).toLowerCase();
if(output.indexOf(char) == -1 && char != ' ') {output+=char;}
}
return output;
}
alert(charsInString('This is a sentence'));
As I'm pretty sure what you need cannot be achieved using a single regular expression, I offer a more general solution:
// collapseSentences(ary) will collapse each sentence in ary
// into a string containing its constituent chars
// #param {Array} the array of strings to collapse
// #return {Array} the collapsed sentences
function collapseSentences(ary){
var result=[];
ary.forEach(function(line){
var tmp={};
line.toLowerCase().split('').forEach(function(c){
if(c >= 'a' && c <= 'z') {
tmp[c]++;
}
});
result.push(Object.keys(tmp).join(''));
});
return result;
}
which should do what you want except that the order of characters in each sentence cannot be guaranteed to be preserved, though in most cases it is.
Given:
var index=['This is a sentence','This is a test','this is another test'],
result=collapseSentences(index);
result contains:
["thisaenc","thisae", "thisanoer"]
(\w)(?<!.*?\1)
This yields a match for each of the right characters, but as if you were reading right-to-left instead.
This finds a word character, then looks ahead for the character just matched.
Nevermind, i managed:
justC = "";
if (color[i+1].match(/A/g)) {justC += " L_A";}
if (color[i+1].match(/B/g)) {justC += " L_B";}
if (color[i+1].match(/C/g)) {justC += " L_C";}
if (color[i+1].match(/D/g)) {justC += " L_D";}
if (color[i+1].match(/E/g)) {justC += " L_E";}
else {color[i+1] = "L_F";}
It's not exactly what my question may have lead to belive is what i wanted, but the printout for this is what i was after, for use in a class: <span class="L_A L_C L_E"></span>
How about:
var re = /(.)((.*?)\1)/g;
var str = 'This is a sentence';
x = str.toLowerCase();
x = x.replace(/ /g, '');
while(x.match(re)) {
x=x.replace(re, '$1$3');
}
I don't think this can be done in one fell regex swoop. You are going to need to use a loop.
While my example was not written in your language of choice, it doesn't seem to use any regex features not present in javascript.
perl -e '$foo="This is a sentence"; while ($foo =~ s/((.).*?)\2/$1/ig) { print "<$1><$2><$foo>\n"; } print "$foo\n";'
Producing:
This aenc