Replace occurance in a string with the result - javascript

I have the following string:
{"key1":"value1","key2":"value2","key3":"value3"}
I want to convert it into this:
{key1:"value1",key2:"value2",key3:"value3"}
So I did something like this:
var output = str.replace(/"(.*?)":/, "$1:");
This way I get:
{key1:"value1","key2":"value2","key3":"value3"}
So it works for the first key, but not for the rest. How can I use the replace method to replace all occurrences like I showed here?

Use a global flag with your regex
str.replace(/"(.*?)":/g, "$1:");

You need to change the regex:
var output = str.replace(/"(.*?)":/g, "$1:");

Related

Javascript: add a character to a string containing a specific word

If I have the following string: table.row.columns.values.many. I am looking to add character * after values.
So expected output would be: table.row.columns.values*.many .
If there is no "values" in string then string should stay the same.
Please use this code.
let str = "table.row.columns.values.many"
str = str.replace("values", "values*");
console.log(str);
You can use also "replaceAll" if you want to replace all "values".
I think this works nice for you, really simple, and easy way
var str = "table.row.columns.values.many";
str = str.replace("values", "values*")
console.log(str)

How to get youku video id from url by regex?

I need to get youku video id from url by regex, for example:
http://v.youku.com/v_show/id_XNTg3OTc3MzY4.html
I only need XNTg3OTc3MzY4 to keep in a variable.
How can I write it in function below
var youkuEmbed = "[[*supplier-video]]";
var youkuUrl = youkuEmbed.match(/http://v\.youku\.com/v_show/id_(\w+)\.html/);
I tried this but it didn't work.
Thanks!
You can use a simple regex like this:
id_(\w+)
Working demo
The idea is to match the _id and the capture all the alphanumeric strings.
MATCH 1
1. [29-42] `XNTg3OTc3MzY4`
If you go the Code Generator section you can get the code. However, you can use something like this:
var myString = 'http://v.youku.com/v_show/id_XNTg3OTc3MzY4.html';
var myRegexp = /id_(\w+)/;
var match = myRegexp.exec(myString);
alert(match[1]);
//Shows: XNTg3OTc3MzY4
You can use this regex:
http://v\.youku\.com/v_show/id_(\w+)\.html
Your match is in the first capturing group.
Here is a regex demo.
Id the id always follows id_, you could possibly split the string.
'http://v.youku.com/v_show/id_XNTg3OTc3MzY4.html'.split(/.*id_|\./)[1]
//=> 'XNTg3OTc3MzY4'
For this specific string, you could just do.
'http://youku.com/id_XNTg30Tc3MzY4.html'.split(/id_|\./)[2]
//=> 'XNTg3OTc3MzY4'
It looks like you need to escape all the slashes because that's the delimiter for the regex itself:
var youkuUrl = youkuEmbed.match(/http:\/\/v\.youku\.com\/v_show\/id_(\w+)\.html/);
Then use the first capture group, as Unihedron stated.

Parse string in javascript

How can I parse this string on a javascript,
var string = "http://www.facebook.com/photo.php?fbid=322916384419110&set=a.265956512115091.68575.100001022542275&type=1";
I just want to get the "265956512115091" on the string. I somehow parse this string but, still not enough to get what I wanted.
my code:
var newstring = string.match(/set=[^ ]+/)[0];
returns:
a.265956512115091.68575.100001022542275&type=1
try this :
var g=string.match(/set=[a-z]\.([^.]+)/);
g[1] will have the value
http://jsbin.com/anuhog/edit#source
You could use split() to modify your code like this:
var newstring = string.match(/set=[^ ]+/)[0].split(".")[1];
For a more generic approach to parsing query strings see:
Parse query string in JavaScript
Using the example illustrated there, you would do the following:
var newstring = getQueryVariable("set").split(".")[1];
You can use capturing group in the regex.
const str = 'http://www.facebook.com/photo.php?fbid=322916384419110&set=a.265956512115091.68575.100001022542275&type=1';
console.log(/&set=(.*)&/.exec(str)[1]);

Simple Javascript string manipulation

I have a string that will look something like this:
I'm sorry the code "codehere" is not valid
I need to get the value inside the quotes inside the string. So essentially I need to get the codehere and store it in a variable.
After some researching it looks like I could loop through the string and use .charAt(i) to find the quotes and then pull the string out one character at a time in between the quotes.
However I feel there has to be a simpler solution for this out there. Any input would be appreciated. Thanks!
You could use indexOf and lastIndexOf to get the position of the quotes:
var openQuote = myString.indexOf('"'),
closeQuote = myString.lastIndexOf('"');
Then you can validate they are not the same position, and use substring to retrieve the code:
var code = myString.substring(openQuote, closeQuote + 1);
Regex:
var a = "I'm sorry the code \"codehere\" is not valid";
var m = a.match(/"[^"]*"/ig);
alert(m[0]);
Try this:
var str = "I'm sorry the code \"cod\"eh\"ere\" is not valid";
alert(str.replace(/^[^"]*"(.*)".*$/g, "$1"));
You could use Javascript's match function. It takes as parameter, a regular expression. Eg:
/\".*\"/
Use regular expressions! You can find a match using a simple regular expressions like /"(.+)"/ with the Javascript RegExp() object. Fore more info see w3schools.com.
Try this:
var msg = "I'm sorry the code \"codehere\" is not valid";
var matchedContent = msg.match(/\".*\"/ig);
//matchedContent is an array
alert(matchedContent[0]);
You should use a Regular Expression. This is a text pattern matcher that is built into the javascript language. Regular expressions look like this: /thing to match/flags* for example, /"(.*)"/, which matches everything between a set of quotes.
Beware, regular expressions are limited -- they can't match nested things, so if the value inside quotes contains quotes itself, you'll end up with a big ugly mess.
*: or new RegExp(...), but use the literal syntax; it's better.
You could always use the .split() string function:
var mystring = 'I\'m sorry the code "codehere" is not valid' ;
var tokens = [] ;
var strsplit = mystring.split('\"') ;
for(var i=0;i<strsplit.length;i++) {
if((i % 2)==0) continue; // Ignore strings outside the quotes
tokens.push(strsplit[i]) ; // Store strings inside quotes.
}
// Output:
// tokens[0] = 'codehere' ;

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