I want to convert a string such as 'String' to the stripped version of that (I think thats the word?), something like this:
const strip = r => {
/* Code */
}
What I want is:
> strip('String')
> String
basically I just want it to remove the quotes from around a string
(I want the output to be a none-type)
Is this what you are after?
var test = "\"'String \" with 'quotes'\"";
test = test.replace(/['"]/g, "");
console.log("test: " + test);
In your example, the string passed as an argument to the strip function does not have quotes in its content. You're just telling that function that the r parameter is of type string with the content String.
To answer to your question, you can remove the quotes of a string by removing the first and last character:
const strip = str => {
return str.slice(1, -1);
}
strip('"String"') => String
Related
I have a string
var st = "asv_abc1_100x101, asv_def2_100x102, asv_ghi1_100x103, asv_jkl4_100x104"
Now I want to put a double quote around each substring
i.e required string
var st = ""asv_abc1_100x101", "asv_def2_100x102", "asv_ghi1_100x103", "asv_jkl4_100x104""
Is this possible to achieve anything like this in javascript?
If you meant to transform a string containing "words" separated by comma in a string with those same "words" wrapped by double quotes you might for example split the original string using .split(',') and than loop through the resulting array to compose the output string wrapping each item between quotes:
function transform(value){
const words = value.split(',');
let output = '';
for(word of words){
output += `"${word.trim()}", `;
}
output = output.slice(0, -2);
return output;
}
const st = "asv_abc1_100x101, asv_def2_100x102, asv_ghi1_100x103, asv_jkl4_100x104";
const output = transform(st);
console.log(output);
That's true unless you just meant to define a string literal containing a character that just needed to be escaped. In that case you had several ways like using single quotes for the string literal or backticks (but that's more suitable for template strings). Or just escape the \" inside your value if you are wrapping the literal with double quotes.
You can use backticks ``
var st = `"asv_abc1_100x101", "asv_def2_100x102", "asv_ghi1_100x103", "asv_jkl4_100x104"`
You can split the string by the comma and space, map each word to a quote-wrapped version of it and then join the result again:
const result = myString
.split(', ')
.map(word => `"${word}"`)
.join(', ')
Also you can transform your string with standard regular expressions:
// String
let st = "asv_abc1_100x101, asv_def2_100x102, asv_ghi1_100x103, asv _ jkl4 _ 100x104";
// Use regular expressions to capture your pattern,
// which is based on comma separator or end of the line
st = st.replace(/(.+?)(,[\s+]*|$)/g, `"$1"$2`);
// Test result
console.log(st);
Working with Javascript I need to be able to search a string input from a user and replace occurrences of semicolons with commas. Issue I have ran into is I need to be able to search the string for any commas that already exist, and quote around to the last and next occurrence of the semicolon.
Example:
User input is 12345;Joran,Michael;02;17;63 it should be converted to 12345,"Joran,Michael",02,17,63
My includes is able to locate the occurrence of a comma in the original string var srch = source.includes(","); and my replace is var converted = source.replace(/;/g, ","); which works fine, just need to figure out how to get to the last/next semicolon to place the quotes.
Using an if/else depending on if srch evaluates to True -- if true, add the quotes and then convert the rest of the string and return to the user; if false, convert and return.
I'm sure there's a way to do this with regex that just hasn't came to me yet so any suggestions on what to look at would be great.
I'd do this in two steps. First match non-; characters which have at least one ,, and surround them with quotes. Then replace all ;s in the result with ,:
console.log(
'12345;Joran,Michael;02;17;63'
.replace(/[^;,]*,[^;]*/g, '"$&"')
.replace(/;/g, ',')
);
Split the string by ;
.split(';')
which gives you an array.
Convert the elements that include a ',' to "${element}"
.map(s => s.includes(',') ? `"${s}"` : s )
Convert the array back to string
.join(',')
var str = '12345;Joran,Michael;02;17;63';
var arr = str.split(";");
var letters = /^[A-Za-z]/;
var final_str = "";
for (var i = 0; i < arr.length; i++) {
final_str = arr[i].match(letters)?final_str +'"'+ arr[i]+'"'+",":final_str + arr[i]+",";
}
console.log(final_str.substring(0,final_str.length -1));
I am trying below code:-
var testrename = {
check: function() {
var str = 988,000 PTS;
var test = str.toString().split(/[, ]/);
console.log(test[0] + test[1]);
}
}
testrename.check();
I want output as- 988000
I was trying it on node
Your str variable's assigned value needs to be quoted in order to assign a string value to it, and for it to be recognized as a string.
It looks like what you're trying to do is extract the integer value of a string, so return 988000 from the string "988,000 PTS", and you would use parseInt(string) for that.
Update: The comma will break the parseInt function and return a truncated number, (988 not 988000) so you can use the replace function with a regular expression to remove all non-numeric values from the string first.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt
var testrename={
check :function() {
var str ="988,000 PTS";
cleanStr = str.replace(/\D/g,'');
var test = parseInt(cleanStr);
console.log(test);
}
} testrename.check();
I have a string that looks like this 'a,b,"c,d",e,"f,g,h"'.
I would like to be able to split this string on , but leave encapsulated strings intact getting the following output : ["a","b","c,d","e","f,g,h"].
Is there a way to do this without having to parse the string char by char ?
You can create a match of the strings, then map the matches and replace any " in the elements:
let f = 'a,b"c,d",e,"f,g,h"';
let matches = f.match(/\w+|(["]).*?\1/g);
let res = matches.map(e => e.replace(/"/g, ''));
console.log(res);
Suppose I have in text.txt:
prop:"txt1" prop:'txt4' prop:"txt13"
And I want it to become (adding 9):
prop:"txt10" prop:'txt13' prop:"txt22"
In javascript, it would be:
var output = input.replace(/prop:(['"])txt(\d+)\1/g, function(match, quote, number){
return "prop:" + quote + "txt" + (parseInt(number) + 9) + quote;
});
I'm trying to code the above code in C#:
string path = #"C:/text.txt";
string content = File.ReadAllText(path);
File.WriteAllText(path, Regex.Replace(content, "prop:(['\"])txt(\\d+)\\1", ?????));
Visual Studio shows the third parameter should be MatchEvaluator evaluator. But I don't know how to declare/write/use it.
Any help is welcome. Thanks for your time.
You can use a Match evaluator and use Int32.Parse to parse the number as an int value that you can add 9 to:
Regex.Replace(content, #"prop:(['""])txt(\d+)\1",
m => string.Format("prop:{0}txt{1}{0}",
m.Groups[1].Value,
(Int32.Parse(m.Groups[2].Value) + 9).ToString()))
See IDEONE demo:
var content = "prop:\"txt1\" prop:'txt4' prop:\"txt13\"";
var r = Regex.Replace(content, #"prop:(['""])txt(\d+)\1",
m => string.Format("prop:{0}txt{1}{0}",
m.Groups[1].Value,
(Int32.Parse(m.Groups[2].Value) + 9).ToString()));
Console.WriteLine(r); // => prop:"10" prop:'13' prop:"22"
Note that I am using a verbatim string literal so as to use a single backslash to escape special characters and define shorthand character classes (however, in a verbatim string literal a double quote must be doubled to denote a single literal double quote).
MatchEvaluator is a delegate. You need to write a function that takes a Match and returns the replacement value. One way to do this is shown below:
private static string AddEvaluator(Match match)
{
int newValue = Int32.Parse(match.Groups[2].Value) + 9;
return String.Format("prop:{0}txt{1}{0}", match.Groups[1].Value, newValue)
}
public static void Main()
{
string path = #"C:/text.txt";
string content = File.ReadAllText(path);
File.WriteAllText(path, Regex.Replace(content, "prop:(['\"])txt(\\d+)\\1", AddEvaluator));
}