My string looks like
"<!number|Foo bar> <!number|Foo bar> <!number|foo bar>"
I have like to split the string by "<" and ">" so that the new array becomes
["<!number|string>", "<!number|string>" ].
I tried str.split('> <'), which gives me
["<!numer|string", "!number|string>"].
Also I tried using regex to str.split(/\<> /)
which gives me ["<!number|string> <!number|string>"].
How to split it correctly?
At work so I can't fix the nitty gritty with the regex, but the below works given the string
const str = `<!1|Foo bar> <!2|Bar Baz> <!3| xxx yyy>`;
console.log(str.split(/(<[\s\S]*?>)/gm).filter((n)=> { return (n!="" && n!=" ") }));
Just split on space:
let str = "<!number|string> <!number|string> <!number|string>";
console.log(str.split(" "));
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);
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);
I'm trying to split a string on "," but I don't want to split if "," is in "{}". There's no nested braces.
here is the string I want to split :
EmbiBISupplierKPIResult_EditArea00001,EmbiBISupplierKPISearch,partyId=E10021&economicAreaPartyIds={DPP_20246, DPP_14726}&economicId={DPP_20246, DPP_14726}&requestedDateSearchType=ACTUAL_WEEK
Here is the result I expect :
EmbiBISupplierKPIResult_EditArea00001
EmbiBISupplierKPISearch
partyId=E10021&economicAreaPartyIds={DPP_20246, DPP_14726}&economicId={DPP_20246, DPP_14726}&requestedDateSearchType=ACTUAL_WEEK
Is there a regex to do this ?
You can use match and be explicit about the optional matching of parts between braces:
var parts = s.match(/(\{[^{}]*\}|[^,{}]+)+/g)
var s = 'EmbiBISupplierKPIResult_EditArea00001,EmbiBISupplierKPISearch,partyId=E10021&economicAreaPartyIds={DPP_20246, DPP_14726}&economicId={DPP_20246, DPP_14726}&requestedDateSearchType=ACTUAL_WEEK';
var parts = s.match(/(\{[^{}]*\}|[^,{}]+)+/g)
document.querySelector('pre').innerHTML = JSON.stringify(parts,null,'\t');
<pre id=result></pre>
You can use the following:
,(?=(?:[^{}]*{[^{}]*})*[^{}]*$)
See DEMO
Is there an easy way to make this string:
(53.5595313, 10.009969899999987)
to this String
[53.5595313, 10.009969899999987]
with JavaScript or jQuery?
I tried with multiple replace which seems not so elegant to me
str = str.replace("(","[").replace(")","]")
Well, since you asked for regex:
var input = "(53.5595313, 10.009969899999987)";
var output = input.replace(/^\((.+)\)$/,"[$1]");
// OR to replace all parens, not just one at start and end:
var output = input.replace(/\(/g,"[").replace(/\)/g,"]");
...but that's kind of complicated. You could just use .slice():
var output = "[" + input.slice(1,-1) + "]";
For what it's worth, to replace both ( and ) use:
str = "(boob)";
str = str.replace(/[\(\)]/g, ""); // yields "boob"
regex character meanings:
[ = start a group of characters to look for
\( = escape the opening parenthesis
\) = escape the closing parenthesis
] = close the group
g = global (replace all that are found)
Edit
Actually, the two escape characters are redundant and eslint will warn you with:
Unnecessary escape character: ) no-useless-escape
The correct form is:
str.replace(/[()]/g, "")
var s ="(53.5595313, 10.009969899999987)";
s.replace(/\((.*)\)/, "[$1]")
This Javascript should do the job as well as the answer by 'nnnnnn' above
stringObject = stringObject.replace('(', '[').replace(')', ']')
If you need not only one bracket pair but several bracket replacements, you can use this regex:
var input = "(53.5, 10.009) more stuff then (12) then (abc, 234)";
var output = input.replace(/\((.+?)\)/g, "[$1]");
console.log(output);
[53.5, 10.009] more stuff then [12] then [abc, 234]
I have a variable string in my JavaScript code containing a comma delimited list of words and or phrases, for example:
String 1 : “abc, def hij, klm”
String 2 : “abc, def”
I want to insert the word ‘and’ after the last comma in the string to get
String 1 : “abc, def hij, and klm”
String 2 : “abc, and def”
I put together the following code:
// replace the last comma in the list with ", and"
var regEx1 = new RegExp(",(?=[A-z ]*$)" )
var commaDelimList = commaDelimList.replace(regEx1, ", and ");
The problem is that it does not work if the comma delimited string has only two items separated by one comma.
So the results of the above example are
String 1 : ”abc, def hij, and klm”
String 2 : “abc, def”
Why is the RegExp not working and what can I use to get the result I want?
Not sure a regex was the right way to go there...
Why not use LastIndexOf and replace that with your string?
Since this is a relatively straight forward task, a little string manipulation may be beneficial - you'll realize better performance too.
var str = 'abc, def, hij, klm',
index = str.lastIndexOf(','),
JOINER = ', and';
//'abc, def, hij, and klm'
str.slice(0, index) + JOINER + str.slice(index+1);
Haven't tried you one but this works
'abc, def'.replace( /,(?=[A-z ]*$)/, ", and" )