This question already exists:
Polymer reset parameters format not working
Closed 2 years ago.
I have a string that outputs like this:
"firstName" "lastName"
I need to the output to be like
"firtName lastName"
or else I get bad string request. I have tried different regex combinations that could achieve that however so far I can remove the quotes at the beginning and end of the string and the ones in the middle.
var string = '"firstName" ,"lastName"';
var stringWithoutCommas = string.replace(/,/g, '');
var stringWithoutExtQuotes = stringWithoutCommas.replace(/^"(.+(?="$))"$/, '$1');
console.log(stringWithoutExtQuotes); //firstName" "lastName
thanks you.
var string = '"firstName" ,"lastName"';
console.log(
string.replace(/"(\w*)\W*(\w*)"/, function(_, match1, match2){
return `"${match1} ${match2}"`;
})
);
You could grab the two strings and rebuild the string you want.
One approach
const input = '"firstName" "lastName"'
console.log('"'+input.replace(/"(.+?)"/g,'$1')+'"')
Extract all between double quotes and join the results:
const string = '"firstName" ,"lastName"';
console.log(Array.from(string.matchAll(/"([^"]+)"/g), x=>x[1]).join(" "));
Regex: "([^"]+)"
Explanation
--------------------------------------------------------------------------------
" '"'
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
[^"]+ any character except: '"' (1 or more
times (matching the most amount
possible))
--------------------------------------------------------------------------------
) end of \1
--------------------------------------------------------------------------------
" '"'
See proof.
This should be answer to your question.
function myFunction() {
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var result = fruits.join(",");
}
Related
Sorry for one more to the tons of regexp questions but I can't find anything similar to my needs. I want to output the string which can contain number or letter 'A' as the first symbol and numbers only on other positions. Input is any string, for example:
---INPUT--- -OUTPUT-
A123asdf456 -> A123456
0qw#$56-398 -> 056398
B12376B6f90 -> 12376690
12A12345BCt -> 1212345
What I tried is replace(/[^A\d]/g, '') (I use JS), which almost does the job except the case when there's A in the middle of the string. I tried to use ^ anchor but then the pattern doesn't match other numbers in the string. Not sure what is easier - extract matching characters or remove unmatching.
I think you can do it like this using a negative lookahead and then replace with an empty string.
In an non capturing group (?:, use a negative lookahad (?! to assert that what follows is not the beginning of the string followed by ^A or a digit \d. If that is the case, match any character .
(?:(?!^A|\d).)+
var pattern = /(?:(?!^A|\d).)+/g;
var strings = [
"A123asdf456",
"0qw#$56-398",
"B12376B6f90",
"12A12345BCt"
];
for (var i = 0; i < strings.length; i++) {
console.log(strings[i] + " ==> " + strings[i].replace(pattern, ""));
}
You can match and capture desired and undesired characters within two different sides of an alternation, then replace those undesired with nothing:
^(A)|\D
JS code:
var inputStrings = [
"A-123asdf456",
"A123asdf456",
"0qw#$56-398",
"B12376B6f90",
"12A12345BCt"
];
console.log(
inputStrings.map(v => v.replace(/^(A)|\D/g, "$1"))
);
You can use the following regex : /(^A)?\d+/g
var arr = ['A123asdf456','0qw#$56-398','B12376B6f90','12A12345BCt', 'A-123asdf456'],
result = arr.map(s => s.match(/(^A|\d)/g).join(''));
console.log(result);
I'm trying to extract out a group of words from a larger string/cookie that are separated by hyphens. I would like to replace the hyphens with a space and set to a variable. Javascript or jQuery.
As an example, the larger string has a name and value like this within it:
facility=34222%7CConner-Department-Store;
(notice the leading "C")
So first, I need to match()/find facility=34222%7CConner-Department-Store; with regex. Then break it down to "Conner Department Store"
var cookie = document.cookie;
var facilityValue = cookie.match( REGEX ); ??
var test = "store=874635%7Csomethingelse;facility=34222%7CConner-Department-Store;store=874635%7Csomethingelse;";
var test2 = test.replace(/^(.*)facility=([^;]+)(.*)$/, function(matchedString, match1, match2, match3){
return decodeURIComponent(match2);
});
console.log( test2 );
console.log( test2.split('|')[1].replace(/[-]/g, ' ') );
If I understood it correctly, you want to make a phrase by getting all the words between hyphens and disallowing two successive Uppercase letters in a word, so I'd prefer using Regex in that case.
This is a Regex solution, that works dynamically with any cookies in the same format and extract the wanted sentence from it:
var matches = str.match(/([A-Z][a-z]+)-?/g);
console.log(matches.map(function(m) {
return m.replace('-', '');
}).join(" "));
Demo:
var str = "facility=34222%7CConner-Department-Store;";
var matches = str.match(/([A-Z][a-z]+)-?/g);
console.log(matches.map(function(m) {
return m.replace('-', '');
}).join(" "));
Explanation:
Use this Regex (/([A-Z][a-z]+)-?/g to match the words between -.
Replace any - occurence in the matched words.
Then just join these matches array with white space.
Ok,
first, you should decode this string as follows:
var str = "facility=34222%7CConner-Department-Store;"
var decoded = decodeURIComponent(str);
// decoded = "facility=34222|Conner-Department-Store;"
Then you have multiple possibilities to split up this string.
The easiest way is to use substring()
var solution1 = decoded.substring(decoded.indexOf('|') + 1, decoded.length)
// solution1 = "Conner-Department-Store;"
solution1 = solution1.replace('-', ' ');
// solution1 = "Conner Department Store;"
As you can see, substring(arg1, arg2) returns the string, starting at index arg1 and ending at index arg2. See Full Documentation here
If you want to cut the last ; just set decoded.length - 1 as arg2 in the snippet above.
decoded.substring(decoded.indexOf('|') + 1, decoded.length - 1)
//returns "Conner-Department-Store"
or all above in just one line:
decoded.substring(decoded.indexOf('|') + 1, decoded.length - 1).replace('-', ' ')
If you want still to use a regular Expression to retrieve (perhaps more) data out of the string, you could use something similar to this snippet:
var solution2 = "";
var regEx= /([A-Za-z]*)=([0-9]*)\|(\S[^:\/?#\[\]\#\;\,']*)/;
if (regEx.test(decoded)) {
solution2 = decoded.match(regEx);
/* returns
[0:"facility=34222|Conner-Department-Store",
1:"facility",
2:"34222",
3:"Conner-Department-Store",
index:0,
input:"facility=34222|Conner-Department-Store;"
length:4] */
solution2 = solution2[3].replace('-', ' ');
// "Conner Department Store"
}
I have applied some rules for the regex to work, feel free to modify them according your needs.
facility can be any Word built with alphabetical characters lower and uppercase (no other chars) at any length
= needs to be the char =
34222 can be any number but no other characters
| needs to be the char |
Conner-Department-Store can be any characters except one of the following (reserved delimiters): :/?#[]#;,'
Hope this helps :)
edit: to find only the part
facility=34222%7CConner-Department-Store; just modify the regex to
match facility= instead of ([A-z]*)=:
/(facility)=([0-9]*)\|(\S[^:\/?#\[\]\#\;\,']*)/
You can use cookies.js, a mini framework from MDN (Mozilla Developer Network).
Simply include the cookies.js file in your application, and write:
docCookies.getItem("Connor Department Store");
I have a string like this:
var str = " this is a [link][1]
[1]: http://example.com
and this is a [good website][2] in my opinion
[2]: http://goodwebsite.com
[3]: http://example.com/fsadf.jpg
[![this is a photo][3]][3]
and there is some text hare ..! ";
Now I want this:
var newstr = "this is a [link][1]
and this is a [good website][2] in my opinion
[![this is a photo][3]][3]
and there is some text hare ..!
[1]: http://example.com
[2]: http://goodwebsite.com
[3]: http://example.com/fsadf.jpg"
How can I do that?
In reality, that variable str is the value of a textarea ... and I'm trying to create a markdown editor .. So what I want is exactly the same with what SO's textarea does.
Here is my try:
/^(\[[0-9]*]:.*$)/g to select [any digit]: in the first of line
And I think I should create a group for that using () and then replace it with \n\n $1
try this:
strLinksArray = str.match(/(\[\d+\]\:\s*[^\s\n]+)/g);
strWithoutLinks = str.replace(/(\[\d+\]\:\s*[^\s\n]+)/g, ''); //removed all links
Here you will get links as array and string without links then do whatever changes you want.
You can use
var re = /^(\[[0-9]*]:)\s*(.*)\r?\n?/gm; // Regex declaration
var str = 'this is a [link][1]\n[1]: http://example.com\nand this is a [good website][2] in my opinion\n[2]: http://goodwebsite.com\n[3]: http://example.com/fsadf.jpg\n[![this is a photo][3]][3]\nand there is some text hare ..!';
var links = []; // Array for the links
var result = str.replace(re, function (m, g1, g2) { // Removing the links
links.push(" " + g1 + " " + g2); // and saving inside callback
return ""; // Removal happens here
});
var to_add = links.join("\n"); // Join the links into a string
document.getElementById("tinput").value = result + "\n\n\n" + to_add; // Display
<textarea id="tinput"></textarea>
See regex demo at regex101.com.
Regex explanation:
^ - start of line (due to the /m modifier)
(\[[0-9]*]:) - Group 1 (referred to as g1 in the replace callback) matching...
\[ - opening square bracket
[0-9]* - zero or more digits
] - closing square bracket
: - a colon
\s* - zero or more whitespace
(.*) - Group 2 matching (g2) zero or more characters other than newline
\r?\n? - one or zero \r followed by one or zero \n
/gm - define global search and replace and ^ matches line start instead of string start
How can I retrieve the word my from between the two rounded brackets in the following sentence using a regex in JavaScript?
"This is (my) simple text"
console.log(
"This is (my) simple text".match(/\(([^)]+)\)/)[1]
);
\( being opening brace, ( — start of subexpression, [^)]+ — anything but closing parenthesis one or more times (you may want to replace + with *), ) — end of subexpression, \) — closing brace. The match() returns an array ["(my)","my"] from which the second element is extracted.
var txt = "This is (my) simple text";
re = /\((.*)\)/;
console.log(txt.match(re)[1]);
jsFiddle example
You may also try a non-regex method (of course if there are multiple such brackets, it will eventually need looping, or regex)
init = txt.indexOf('(');
fin = txt.indexOf(')');
console.log(txt.substr(init+1,fin-init-1))
For anyone looking to return multiple texts in multiple brackets
var testString = "(Charles) de (Gaulle), (Paris) [CDG]"
var reBrackets = /\((.*?)\)/g;
var listOfText = [];
var found;
while(found = reBrackets.exec(testString)) {
listOfText.push(found[1]);
};
Use this to get text between closest ( and ):
const string = "This is (my) (simple (text)"
console.log( string.match(/\(([^()]*)\)/)[1] )
console.log( string.match(/\(([^()]*)\)/g).map(function($0) { return $0.substring(1,$0.length-1) }) )
Results: my and ["my","text"].
EXPLANATION
--------------------------------------------------------------------------------
\( '('
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
[^()]* any character except: '(', ')' (0 or
more times (matching the most amount
possible))
--------------------------------------------------------------------------------
) end of \1
--------------------------------------------------------------------------------
\) ')'
to get fields from string formula.
var txt = "{{abctext/lsi)}} = {{abctext/lsi}} + {{adddddd}} / {{ttttttt}}";
re = /\{{(.*?)\}}/g;
console.log(txt.match(re));
to return multiple items within rounded brackets
var res2=str.split(/(|)/);
var items=res2.filter((ele,i)=>{
if(i%2!==0) {
return ele;
}
});
I have this string for example:
str = "my name is john#doe oh.yeh";
the end result I am seeking is this Array:
strArr = ['my','name','is','john','&#doe','oh','&yeh'];
which means 2 rules apply:
split after each space " " (I know how)
if there are special characters ("." or "#") then also split but add the characther "&" before the word with the special character.
I know I can strArr = str.split(" ") for the first rule. but how do I do the other trick?
thanks,
Alon
Assuming the result should be '&doe' and not '&#doe', a simple solution would be to just replace all . and # with & split by spaces:
strArr = str.replace(/[.#]/g, ' &').split(/\s+/)
/\s+/ matches consecutive white spaces instead of just one.
If the result should be '&#doe' and '&.yeah' use the same regex and add a capture:
strArr = str.replace(/([.#])/g, ' &$1').split(/\s+/)
You have to use a Regular expression, to match all special characters at once. By "special", I assume that you mean "no letters".
var pattern = /([^ a-z]?)[a-z]+/gi; // Pattern
var str = "my name is john#doe oh.yeh"; // Input string
var strArr = [], match; // output array, temporary var
while ((match = pattern.exec(str)) !== null) { // <-- For each match
strArr.push( (match[1]?'&':'') + match[0]); // <-- Add to array
}
// strArr is now:
// strArr = ['my', 'name', 'is', 'john', '&#doe', 'oh', '&.yeh']
It does not match consecutive special characters. The pattern has to be modified for that. Eg, if you want to include all consecutive characters, use ([^ a-z]+?).
Also, it does nothing include a last special character. If you want to include this one as well, use [a-z]* and remove !== null.
use split() method. That's what you need:
http://www.w3schools.com/jsref/jsref_split.asp
Ok. i saw, you found it, i think:
1) first use split to the whitespaces
2) iterate through your array, split again in array members when you find # or .
3) iterate through your array again and str.replace("#", "&#") and str.replace(".","&.") when you find
I would think a combination of split() and replace() is what you are looking for:
str = "my name is john#doe oh.yeh";
strArr = str.replace('\W',' &');
strArr = strArr.split(' ');
That should be close to what you asked for.
This works:
array = string.replace(/#|\./g, ' &$&').split(' ');
Take a look at demo here: http://jsfiddle.net/M6fQ7/1/