I need match string in quotes - javascript

I need to match string within "" , I'm using following it's not working
var str='"hi" hello "abc\nddk" ef "gh"';
console.log(str.match(/(?=")[^"]*?(?=")/));
t's giving me output as
[]
I need output as
["hi", "abc\nddk", "gh"]
Update :
I can use regex "[^"]" to match string in quotes but I need to avoid the " from the result

Simplest way would be to do:
/"[^"]*?"/g
This will return an array with "hi", "abc\nddk" and "gh" and you can do something like piece.replace(/"/g, "") on individual pieces to get rid of the ". If you don't like that then rather than do a match you can do a search and don't replace
var matches = [];
str.replace(/"([^"]*?)"/g, function (_, match) {
matches.push(match);
});

This should do the trick:
/(?| (")((?:\\"|[^"])+)\1 | (')((?:\\'|[^'])+)\1 )/xg
Demo
BTW: regex101.com is a great resource to use (which is where I got the regex above)
Update
The first one I posted works for PHP, here is one for JS
/"([^"\\]*(?:\\.[^"\\]*)*)"|\w+|'([^'\\]*(?:\\.[^'\\]*)*)'/g

Maybe I read your question incorrectly but this is working for me
/\".+\"/gm
https://regex101.com/r/wF0yN4/1

Related

Splitting string with javascript using '>' character

I acknowledge that this question has probably been asked so many times before and I have tried searching all over StackOverflow for a solution, but so far nothing has worked for me.
I want to split a string but it's not working properly and spitting out individual characters as each item in an array. The string I have from my CMS uses ">" characters to separate and I am using regEx to replace the 'greater than' symbol - with a comma, which works. Sourced this solution from Regex that detects greater than ">" and less than "<" in a string
However, the arrays remain incorrectly formed, like the split() function does not even work:
var myString = "TEST Public Libraries Connect > News Blog > A new item"
var regEx = /<|>/g;
var myNewString = (myString.replace(regEx,","))
alert(myNewString);
myNewString.split(",");
alert(myNewString[0]);
alert(myNewString[1]);
alert(myNewString[2]);
I've put it up in a Fiddle as well, just confused as to why the split won't work properly. Is it because there is spaces in the string?
This should work:
var myNewString = myString.split(">");
https://jsfiddle.net/2j56cva0/3/
In your fiddle, you were splitting myNewString instead of the actual string.
myNewString.split(",");
You need to assign the result of the split to something. It does not just change the string itself into an array.
var parts = myNewString.split(",");

Is it possible to cut off the beginning of a string using regex?

I have a string which contains a path, such as
/foo/bar/baz/hello/world/bla.html
Now, I'd like to get everything from the second-last /, i.e. the result shall be
/world/bla.html
Is this possible using a regex? If so, how?
My current solution is to split the string into an array, and join its last two members again, but I'm sure that there is a better solution than this.
For example:
> '/foo/bar/baz/hello/world/bla.html'.replace(/.*(\/.*\/.*)/, "$1")
/world/bla.html
You can also do
str.split(/(?=\/)/g).slice(-2).join('')
> '/foo/bar/baz/hello/world/bla.html'.match(/(?:\/[^/]+){2}$/)[0]
"/world/bla.html"
Without regular expression:
> var s = '/foo/bar/baz/hello/world/bla.html';
> s.substr(s.lastIndexOf('/', s.lastIndexOf('/')-1))
"/world/bla.html"
I think this will work:
var str = "/foo/bar/baz/hello/world/bla.html";
alert( str.replace( /^.*?(\/[^/]*(?:\/[^/]*)?)$/, "$1") );
This will allow for there being possibly only one last part (like, "foo/bar").
You can use /(\/[^\/]*){2}$/ which selects a slash and some content twice followed by the end of the string.
See this regexplained.

Replace .split() with .match() using regex in javascript

I'm having difficulties with constructing some regular expressions using Javascript.
What I need:
I have a string like: Woman|{Man|Boy} or {Girl|Woman}|Man or Woman|Man etc.
I need to split this string by '|' separator, but I don't want it to be split inside curly brackets.
Examples of strings and desired results:
// Expample 1
string: 'Woman|{Man|Boy}'
result: [0] = 'Woman', [1] = '{Man|Boy}'
// Example 2
string '{Woman|Girl}|{Man|Boy}'
result: [0] = '{Woman|Girl}', [1] = '{Man|Boy}'
I can't change "|" symbol to another inside the brackets because the given strings are the result of a recursive function. For example, the original string could be
'Nature|Computers|{{Girls|Women}|{Boys|Men}}'
try this:
var reg=/\|(?![^{}]+})/g;
Example results:
var a = 'Woman|{Man|Boy}';
var b = '{Woman|Girl}|{Man|Boy}';
a.split(reg)
["Woman", "{Man|Boy}"]
b.split(reg)
["{Woman|Girl}", "{Man|Boy}"]
for your another question:
"Now I have another, but a bit similar problem. I need to parse all containers from the string. Syntax of the each container is {sometrash}. The problem is that container can contain another containers, but I need to parse only "the most relative" container. mystring.match(/\{+.+?\}+/gi); which I use doesn't work correctly. Could you correct this regex, please? "
you can use this regex:
var reg=/\{[^{}]+\}/g;
Example results:
var a = 'Nature|Computers|{{Girls|Women}|{Boys|Men}}';
a.match(reg)
["{Girls|Women}", "{Boys|Men}"]
You can use
.match(/[^|]+|\{[^}]*\}/g)
to match those. However, if you have a nesting of arbitrary depth then you'll need to use a parser, [javascript] regex won't be capable of doing that.
Test this:
([a-zA-Z0-9]*\|[a-zA-Z0-9]*)|{[a-zA-Z0-9]*\|[a-zA-Z0-9]*}

Javascript RegExp matching returning too many

I need to take a string and get some values from it. I have this string:
'tab/tab2/tab3'
The '/tab3' is optional so this string should also work:
'tab/tab2'
I currently am trying this which works for the most part:
'tab/tab2/tab3'.match(new RegExp('^tab/([%a-zA-Z0-9\-\_\s,]+)(/([%a-zA-Z0-9-_s,]+)?)$'));
This will return:
["tab/tab2/tab3", "tab2", "/tab3", "tab3"]
but I want it to return
["tab/tab2/tab3", "tab2", "tab3"]
So I need to get rid of the 3rd index item ("/tab3") and also get it to work with just the 'tab/tab2' string.
To complicate it even more, I only have control over the /([%a-zA-Z0-9-_s,]+)? part in the last grouping meaning it will always wrap in a grouping.
you don't need regex for this, just use split() method:
var str = 'tab/tab2/tab3';
var arr = str.split('/');
console.log(arr[0]); //tab
console.log(arr[1]); //tab2
jsfiddle
I used this regexp to do this:
'tab/tab2/tab3'.match(new RegExp('^tab/([%a-zA-Z0-9\-\_\s,]+)(?:/)([%a-zA-Z0-9-_s,]+)$'));
Now I get this return
["tab/tab2/tab3", "tab2", "tab3"]
Now I just need to allow 'tab/tab2' to be accepted aswell...
Do not put regex between " or ', using /g to make global search else only first occurrence is returned
"tab/tab2/tab3".match(/tab[0-9]/g)

Splitting string in javascript

How can I split the following string?
var str = "test":"abc","test1":"hello,hi","test2":"hello,hi,there";
If I use str.split(",") then I won't be able to get strings which contain commas.
Whats the best way to split the above string?
I assume it's actually:
var str = '"test":"abc","test1":"hello,hi","test2":"hello,hi,there"';
because otherwise it wouldn't even be valid JavaScript.
If I had a string like this I would parse it as an incomplete JSON which it seems to be:
var obj = JSON.parse('{'+str+'}');
and then use is as a plain object:
alert(obj.test1); // says: hello,hi
See DEMO
Update 1: Looking at other answers I wonder whether it's only me who sees it as invalid JavaScript?
Update 2: Also, is it only me who sees it as a JSON without curly braces?
Though not clear with your input. Here is what I can suggest.
str.split('","');
and then append the double quotes to each string
str.split('","'); Difficult to say given the formatting
if Zed is right though you can do this (assuming the opening and closing {)
str = eval(str);
var test = str.test; // Returns abc
var test1 = str.test1; // returns hello,hi
//etc
That's a general problem in all languages: if the items you need contain the delimiter, it gets complicated.
The simplest way would be to make sure the delimiter is unique. If you can't do that, you will probably have to iterate over the quoted Strings manually, something like this:
var arr = [];
var result = text.match(/"([^"]*"/g);
for (i in result) {
arr.push(i);
}
Iterate once over the string and replace commas(,) following a (") and followed by a (") with a (%) or something not likely to find in your little strings. Then split by (%) or whatever you chose.

Categories

Resources