How to wrap comma separated values string in single quotes? [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have the following example of a string:
"label1, label2, label3, label4, label5"
Now, because this will be used as an object initialising a jquery plugin, it needs to look like this:
'label1','label2','label3','label4','label5'
I already managed to split the string with split(","), turning it into an array, however i am not sure how i can wrap each of the array items with single quotes, at which stage, i will be able to join it back to a string for usage?
Any ideas?
solution can be js only or jquery.

You can do it like below. Hope it helps.
var input = "label1, label2, label3, label4, label5";
var result = '\'' + input.split(',').join('\',\'') + '\'';

"label1, label2, label3, label4, label5".split(',').map(function(word){
return "'" + word.trim() + "'";
}).join(',');
(ES6 edit)
"label1, label2, label3, label4, label5".split(',')
.map(word => `'${word.trim()}'`)
.join(',');

Maybe somthing like this:
var str = "label1, label2, label3, label4, label5";
var arr = str.split(",");
for (var i in arr) {
if (arr.hasOwnProperty(i)) {
arr[i] = "'"+arr[i]+"'";
}
}

Split string with comma and space to make array and use join method to get array element separated by separator.
i.e: separator as ',' and also add start and end quote because it is missing after joining elements.
var str = "label1, label2, label3, label4, label5";
var res = str.split(", ");
var data = "'" + res.join("','") + "'";
console.log(data);

Related

how to remove all content in string except dots in js [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 10 months ago.
Improve this question
here is my simple question
const str = _world.(hello)+=.is..to.#%smart+/
can anyone give regex expression for this
output
onlyDots avoid all content
onlyDots = '....'
You can split the string & then filter the dot characters & finally join them back!
const str = "_world.(hello)+=.is..to.#%smart+/";
const result = str.split("").filter(k => k === ".").join("");
console.log(result);
You can simply the count the occurrences of . in the string.
const str = "_world.(hello)+=.is..to.#%smart+/"
let dotCount = 0;
for (let s of str) {
if (s === ".") {
dotCount += 1
}
};
const result = ".".repeat(dotCount);
console.log(result);
If you want to use Regex then you can simply replace all non dot characters into empty string.
const str = "_world.(hello)+=.is..to.#%smart+/"
const res = str.replaceAll(/[^.]/g, "");
console.log(res);
Something like this should work.
const str = "_world.(hello)+=.is..to.#%smart+/";
console.log(str.replace(/[a-zA-Z 0-9!##\$%\^\&*\)\(+='_/-]/g, "."));
To do this in regex you can match all characters that are not a dot, and replace with an empty string:
const str = "_world.(hello)+=.is..to.#%smart+/";
const dots = str.replace(/[^.]/g, "");
console.log(dots); // expected output: .....
First make the following corrections in order to turn your code into valid code:
Enclose the right-hand side in "" so it is a valid string
Then, use String#replace and a regex that can replace more than one non-dot character at a time as follows:
const str = "_world.(hello)+=.is..to.#%smart+/",
output = str.replace(/[^\.]+/g, '');
console.log( output );
Alternatively, you can pass a function to the String#replace method as follows:
const str = "_world.(hello)+=.is..to.#%smart+/",
output = str.replace(/./g, c => c === "." ? "." : "");
console.log( output );

split the string which has hypen [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I would like to know how to split and get the values in the following variable
var str= "send-money-from-united-states-to-hong-kong"
var str1= "send-money-from-thailand-to-singapore"
Expected Output: United States Hong Kong
Expected Output: Thailand Singapore
No need for regular expression here.
This simple code will extract wanted data:
var strArr = "send-money-from-thailand-to-singapore".replace("send-money-from-", "").split("-");
for (i = 0; i < strArr.length; i++) {
// capitalize letters
strArr[i] = strArr[i].charAt(0).toUpperCase() + strArr[i].slice(1);
}
var countries = strArr.join(" ").split(" To ");
console.log(countries[0]);
console.log(countries[1]);
I assumed that strings are in the same format: starting with send-money-from- and countries are divided by -to-.
Solved by the following js.
Could be simplified, but made it stepwise for better understading:
var str = "send-money-from-united-states-to-hong-kong"
str = str.replace("send-money-from-", "");
str = str.replace("-to-", " ");
str = str.replace(/-/g, " ");
str = str.split(" ");
for (i = 0; i < str.length; i++) {
str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1)
}
console.log(str.join(" "));
Using the split function from javascript will help
var strArr = str.split('-')
You'll get an array that you can then manipulate to your liking. So for your expected output you'll want to concatenate the indexes that you require.
var strArr = str.split('-')
var strArr2 = str2.split('-')
console.log(strArr[4], strArr[5], strArr[6], strArr[7])
console.log(strArr2[3], strArr2[5])
Then using a custom function, you can get a title
String.prototype.toProperCase = function () {
return this.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
};
strArr[2].toProperCase()
Lodash can make this manipulation minimized such as:
var strArr = _.map(_.split(str), function(text) { return _.startCase(text) })
And then get the necessary values. In terms of manipulating the array to get the correct values from the string, you will need some sort of template array that has the text that you will accept.
Then you can map through the string array against that template array and only accept the values that fulfill a true condition.
// Remember evaluating case when creating array (LowerCase vs TitleCase)
var templateArray = ['Thailand', 'Singapore']
var strArr = _.map(_.split(str), function(text) { return _.startCase(text) })
var reducer = function(accumulator, currentValue) {
if(templateArray.includes(currentValue)) {
accumulator.push(currentValue)
}
}
var newString = strArr.reduce(reducer, [])

Regular Expression : How to get the value in curly brace except square brackets [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I need to get only "Callout" value in below string using regex in Javascript.
str = "aaa {Callout [apple]} bbbb";
Keep it simple in my opinion. If you want the first match in the string access it by result[0]..
var string = "asdfadsfsad {Callout1 [callout1]} dasdfsadf {Callout2 [callout2]} ccc]";
var result = string.match(/[^{]+(?=\[)/g);
console.log(result[0]); // => "Callout1 "
For all matches just access result directly.
console.log(result); // => [ 'Callout1 ', 'Callout2 ' ]
Regular expression:
[^{]+ any character except: '{' (1 or more times)
(?= look ahead to see if there is:
\[ '['
) end of look-ahead
You can use lookahead and group matching:
\{(\w+)(?=\b)
See Demo
JS code:
var re = new RegExp(/\{(\w+)(?=\b)/);
var m = re.exec("aaa {Callout [apple]} bbbb");
alert(m[1]);
Try this
{(.*?)\[
Regex Demo
var myString = "asdfadsfsad {Callout [callout1]} dasdfsadf {Callout [callout2]} ccc]";
var myRegexp = /{(.*?)\[/g;
var match = myRegexp.exec(myString);
alert(match[1]);
Working JS Fiddle

replace parenthesis opening and closing tags with () tag [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
I am trying to write a string or integer formula which will look a code between parentheses.My logic is this: Search for the first parentheses, find the last parentheses, and return everything in between. Im sure there is a string or integer function, but not exactly sure which one will do the trick. And by the way, the code in between the parentheses varies from length 3 to 9.kindly check this code enter code here
var n;
var $;
var str = document.getElementById("demo").innerHTML;
var p = str.indexOf(")");
var q = str.indexOf("(");
var res = str.replace(")", "");
var re = str.replace("(", "");
document.getElementById("demo").innerHTML = res;
var k = str.replace("$", "(" + "$")
.replace(/,$/, ".")
.replace(")", "(" + res + ")")
.replace("(", "(" + res + ")")
.replace(/O/g, 0)
.replace(/o/g, 0)
.replace(/g/g, 9)
.replace(/\s/g, "");
document.getElementById("demo3").innerHTML = k;
From what I can understand of your question, you just want to search a string of anything and pull out the characters that are surrounded by paranthesis. This is very easy.
var foo = 'blah(capture this)blah';
var result = foo.match(/\(([^()]+)\)/);
//this simply says: capture any characters surrounded by paranthesis, as long as there is at least one character.
console.log(result[1]);
Update based on your comments:
The logic is very easy to follow.
var regex = new RegExp(
'\\(?'+ //optional (
'\\$?'+ //optional $
'(\\d+)' //capture any digit, at least one
);
function format(userInput) {
var results = userInput.match(regex);
if (results === null) { results = [0,0]; }
//get the important part (the digits), format it however you want.
var formatted = '($'+results[1]+'.00)';
return formatted;
}
//all output ($1234.00)
console.log(format('$1234)'));
console.log(format('($1234.00'));
console.log(format('1234'));
console.log(format('1234.0'));
console.log(format('1234)'));
console.log(format('(1234.0'));

Wrap string in brackets but also having random value in string: [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
How can I wrap a string in parantheses that has another random value in it? Look at this for explaining better to understand:
var str = "ss(X)+ss(X)"
INTO:
"(ss(X))+(ss(X))"
NOTE: X can be any value like: "223" or "abc" "2+2+2"
If the string is random data, then this would be impossible, since you don't know what you actually want wrapped. Step 1: find out the condition for "this should be wrapped" versus "this should not be wrapped". We can then do a simple replacement:
var shouldbewrapped = /([a-zA-Z\(\)])+/g;
var wrapped = string.replace(shouldbewrapped, function(found) {
return "(" + found + ")";
});
This does a regexp replace, but instead of replacing a string with a string, it replaces a string with the output of a function run on that string.
(note that the 'g' is crucial, because it makes the replace apply to all matches in your string, instead of stopping after running one replacement)
You can try this:
str = str.replace(/\w*\(\d*\)/g, function () {return '(' + arguments[0] + ')';});
A live demo at jsFiddle
EDIT
Since you've changed the conditions, the task can't be done by Regular Expressions. I've put an example, how you can do this, at jsFiddle. As a side effect, this snippet also detects possible odd brackets.
function addBrackets (string) {
var str = '(' + string,
n, temp = ['('], ops = 0, cls;
str = str.replace(/ /g, '');
arr = str.split('');
for (n = 1; n < arr.length; n++) {
temp.push(arr[n]);
if (arr[n] === '(') {
ops = 1;
while (ops) {
n++;
temp.push(arr[n]);
if (!arr[n]) {
alert('Odd opening bracket found.');
return null;
}
if (arr[n] === '(') {
ops += 1;
}
if (arr[n] === ')') {
ops -= 1;
}
}
temp.push(')');
n += 1;
temp.push(arr[n]);
temp.push('(');
}
}
temp.length = temp.length - 2;
str = temp.join('');
ops = str.split('(');
cls = str.split(')');
if (ops.length === cls.length) {
return str;
} else {
alert('Odd closing bracket found.');
return null;
}
}
Just as a sidenote: If there's a random string within parentheses, like ss(a+b) or cc(c*3-2), it can't be matched by any regular pattern. If you try to use .* special characters to detect some text (with unknown length) within brackets, it fails, since this matches also ), and all the rest of the string too...
I think your going to need to do some string interpolation. Then you can set up some Math.random or whatever you want to generate randomness with.

Categories