How to match space separated strings? - javascript

but not an empty string?
// loop through space separated "tokens" in a string
// will loop through "" - needs update
$P.eachString = function (str, func, con) {
var regexp = /^|\s+/;
if (regexp.test(str)) {
// ... stuff
}
};
The code above will match "" the empty string. I want to match against
case1
some_string
case2
some_string1 some_string2
case3
some_string1 some_string2 some_string_3
etc.

Just use String.split and iterate over the returned array:
Splits a String object into an array of strings by separating the string into substrings.
If separator is omitted, the array contains one element consisting of the entire string.

Related

String (double quote) formatting in Javascript

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);

Split array in a parameter in Javascript

<script>
window.onload = start;
function start() {
word(["S"+"U"+"Z"],["D"+"A"+"R"])
}
function word(a,b) {
var letters = a+b
for (var i = 0; i < letters.length; i++) {
}
document.getElementById("utskrift").innerHTML=letters
}
</script>
Okay so this code works completely fine. My letters come out as "SUZDAR", but i wanna be able to remove the "+" symbol in my argument "Word" and replace it with commas. so the argument becomes (["S","U","Z"],["D","A","R"]). The question is, how do i remove the commas and get the same output as i currently have without the "+" symbols. I dont know how to use the split function here.
Just use the join function:
var letters = a.join('') + b.join('');
Use Array#concat() to merge the 2 arrays and Array#join() to merge array items to string
function word(a,b){
return a.concat(b).join('')
}
console.log(word(["S","U","Z"],["D","A","R"]))
use join() function to combine all your array elements into single string value.
join() function will add a default separator (comma) for each pair of adjacent elements of the array. The separator is converted to a string and the output will be like,
letters.join(); //returns S,U,Z,D,A,R
To remove the ',' value you need to mention empty string ('') as parameter to join function. If separator is an empty string, all elements are joined without any characters in between them.
letters.join(''); //returns SUZDAR

Splitting string but leave inner strings intact?

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);

Regex to get extract parts from String with specific separator, JavaScript

I have example string:
[:pl]Field_value_in_PL[:en]Field_value_in_EN[:]
And I want get something like it:
Object {
pl: "Field_value_in_PL",
en: "Field_value_in_EN"
}
But I cannot assume there will be always "[:pl]" and "[:en]" in input string. There can by only :pl or :en, :de and :fr or any other combination.
I tried to write Regexp for this but I failed.
Try using .match() with RegExp /:(\w{2})/g to match : followed by two alphanumeric characters, .map() to iterate results returned from .match(), String.prototype.slice() to remove : from results, .split() with RegExp /\[:\w{2}\]|\[:\]|:\w{2}/ to remove [, ] characters and matched : followed by two alphanumeric characters, .filter() with Boolean as parameter to remove empty string from array returned by .split(), use index of .map() to set value of object, return object
var str = "[:pl]Field_value_in_PL[:en]Field_value_in_EN[:]:deField_value_in_DE";
var props = str.match(/:(\w{2})/g).map(function(val, index) {
var obj = {}
, prop = val.slice(1)
,vals = str.split(/\[:\w{2}\]|\[:\]|:\w{2}/).filter(Boolean);
obj[prop] = vals[index];
return obj
});
console.log(JSON.stringify(props, null, 2))
Solution with String.replace , String.split and Array.forEach functions:
var str = "[:pl]Field_value_in_PL[:en]Field_value_in_EN[:fr]Field_value_in_FR[:de]Field_value_in_DE[:]",
obj = {},
fragment = "";
var matches = str.replace(/\[:(\w+?)\]([a-zA-Z_]+)/gi, "$1/$2|").split('|');
matches.forEach(function(v){ // iterating through key/value pairs
fragment = v.split("/");
if (fragment.length == 2) obj[fragment[0]] = fragment[1]; // making sure that we have a proper 'final' key/value pair
});
console.log(obj);
// the output:
Object { pl: "Field_value_in_PL", en: "Field_value_in_EN", fr: "Field_value_in_FR", de: "Field_value_in_DE" }
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split
You can try this regex to capture in one group what's inside a pair of brackets and in the other group the group of words that follow the brackets.
(\[.*?\])(\w+)

javascript get substring of string at n of the same char

I have the string:
"A1111A2222A3333A4444"
how do I get the string:
"A1111"
I need to be able to get it by specifying the number of 'A' chars from the end and removing this portion from the total string.
EDIT:
I have a large string separated by the char 'A', for example:
"A11A22A33A44A55A66A77A88A99"
What I need is a function that will give me the substring from 0 to the index of n 'A' chars away. For example, getSubstring(3) would return:
"A11A22A33A44A55A66"
You can:
split the string using the character as the separator
Use slice to get a subarray with all items except the last n items
join back that subarray
function getSubstring(str, ch, n) {
return str.split(ch).slice(0, -n).join(ch);
}
getSubstring("A1111A2222A3333A4444", "A", 3); // "A1111"
getSubstring("A11A22A33A44A55A66A77A88A99", "A", 3); // "A11A22A33A44A55A66"
Given
var str = "A1111A2222A3333A4444";
var pattern = /A1*4/;
search() will tell you at what index the match was found
str.search(pattern)
match() will return 'A1111'. (match accually returns an array with [0] being the string that was searched and [1] being the matched part of the string.
str.match(pattern)[1];

Categories