Separating string with JavaScript - javascript

The goal
99999999 to 9999 9999.
The problem
I searched for String.split, but I couldn't apply. I don't want to separate the string into two variables, I just want to separate the string to displaying proposals.
The scenario
There is the following fragment on my application:
var contactPhone = "91929394";
And I want to separate 91929394 into 9192 9394 by calling the same variable (contactPhone).
Clarifying know-how questions
I really don't know the syntax, even not how I have to search for. Take it easy — it is a programming question.

Use contactPhone.replace(/(\d{4})(\d{4})/, '$1 $2')
It will split the phone number into two groups, with 4 digits each.
If contactPhone is a number and not a string, you can use contactPhone.toString() before using the regex replace.

You could simply;
var formatted = contactPhone.toString();
formatted = formatted.substr(0, 4) + " " + formatted.substr(4);

try this:
function sep(str){
var len = str.length;
var a = len/2;
return str.substring(0, a) + ' ' + str.substring(a, len);
}

If you wanted to be more robust, you could add a space after every 4th character?
contactPhone.replace(/.{1,4}/g, '$& ');

Does this help?
function splitInTwo(s){
return [s.substring(0, s.length/2), s.substring(s.length/2)]
}

Related

Data format transfer by using Reg Ex

I have a batch of strings like
32-1233-21323300
32-dsdw-ee322300
32-ee23-cd3de300
The expectation results after replacement
3451-1233-213.233
3451-dsdw-ee3.223
3451-ee23-cd3.de3
......
What I want is to use regex in a function to transfer the data format.
function dataTransfer('32-xxxx-xxxxxx00', '4351-xxxx-xxx.xxx')
My former code is like:
arrData(d=>{
d = d.replace(/^[32]/,"3451").replace(/[00]$/,"");
d = d.slice(0, 13) + '.' + d.slice(13);
})
But I think there should be other good solution. any suggestion?
Appendix:
Thank you for all feedback.
give up, What I want is to try to analyse format like '32-xxxx-xxxxxx00'. x stands for any char.
User can input param like 32-xxxx-xxxxxx00 and 4351-xx0x-xxx.xx9
I will get source and target format. then I try to analyse the format and use RegEx to complete the data transfer. But It seems too complicated.
May be this regex help you. Try below regex
"32-1233-21323300".replace(/^(32)/,"3451").replace(/([0]+)$/,"").replace(/([0-9a-zA-Z]{3})$/,".$1")
Output : 3451-1233-213.233 as your expectation.
I don't see why your solution is bad but if you want 1 regex instead you can use this:
^(?:32)(-[\da-z]{4}-[\da-z]{3})([\da-z]{3})
It will produce 2 groups and then you can do "3451"+group1+"."+group2 to create your final string
You can make use of /(^32)(.{9})(.{3})(00$)/, merging substrings:
const a = '32-dsdw-ee322300'.replace(/(^32)(.{9})(.{3})(00$)/, `3451$2.$3`)
console.log(a)
You just need these two replace. Check this JS demo.
var arr = ['32-1233-21323300','32-dsdw-ee322300','32-ee23-cd3de300']
for (s of arr) {
console.log(s + " --> " + s.replace(/^32/,'3451').replace(/(.{3})(.{3})00$/,'$1.$2'));
}
You could do this easily without regex:
var s = "32-1233-21323300";
if(s.startsWith("32-") && s.endsWith("00")){
// remove 32- at the beginning
s = "3451-" + s.slice(3);
// remove 00 at the end
s = s.slice(0, s.length - 2);
// insert dot
s = s.slice(0, s.length - 3) + "." + s.slice(s.length - 3);
console.log(s);
}

Regex match cookie value and remove hyphens

I'm trying to extract out a group of words from a larger string/cookie that are separated by hyphens. I would like to replace the hyphens with a space and set to a variable. Javascript or jQuery.
As an example, the larger string has a name and value like this within it:
facility=34222%7CConner-Department-Store;
(notice the leading "C")
So first, I need to match()/find facility=34222%7CConner-Department-Store; with regex. Then break it down to "Conner Department Store"
var cookie = document.cookie;
var facilityValue = cookie.match( REGEX ); ??
var test = "store=874635%7Csomethingelse;facility=34222%7CConner-Department-Store;store=874635%7Csomethingelse;";
var test2 = test.replace(/^(.*)facility=([^;]+)(.*)$/, function(matchedString, match1, match2, match3){
return decodeURIComponent(match2);
});
console.log( test2 );
console.log( test2.split('|')[1].replace(/[-]/g, ' ') );
If I understood it correctly, you want to make a phrase by getting all the words between hyphens and disallowing two successive Uppercase letters in a word, so I'd prefer using Regex in that case.
This is a Regex solution, that works dynamically with any cookies in the same format and extract the wanted sentence from it:
var matches = str.match(/([A-Z][a-z]+)-?/g);
console.log(matches.map(function(m) {
return m.replace('-', '');
}).join(" "));
Demo:
var str = "facility=34222%7CConner-Department-Store;";
var matches = str.match(/([A-Z][a-z]+)-?/g);
console.log(matches.map(function(m) {
return m.replace('-', '');
}).join(" "));
Explanation:
Use this Regex (/([A-Z][a-z]+)-?/g to match the words between -.
Replace any - occurence in the matched words.
Then just join these matches array with white space.
Ok,
first, you should decode this string as follows:
var str = "facility=34222%7CConner-Department-Store;"
var decoded = decodeURIComponent(str);
// decoded = "facility=34222|Conner-Department-Store;"
Then you have multiple possibilities to split up this string.
The easiest way is to use substring()
var solution1 = decoded.substring(decoded.indexOf('|') + 1, decoded.length)
// solution1 = "Conner-Department-Store;"
solution1 = solution1.replace('-', ' ');
// solution1 = "Conner Department Store;"
As you can see, substring(arg1, arg2) returns the string, starting at index arg1 and ending at index arg2. See Full Documentation here
If you want to cut the last ; just set decoded.length - 1 as arg2 in the snippet above.
decoded.substring(decoded.indexOf('|') + 1, decoded.length - 1)
//returns "Conner-Department-Store"
or all above in just one line:
decoded.substring(decoded.indexOf('|') + 1, decoded.length - 1).replace('-', ' ')
If you want still to use a regular Expression to retrieve (perhaps more) data out of the string, you could use something similar to this snippet:
var solution2 = "";
var regEx= /([A-Za-z]*)=([0-9]*)\|(\S[^:\/?#\[\]\#\;\,']*)/;
if (regEx.test(decoded)) {
solution2 = decoded.match(regEx);
/* returns
[0:"facility=34222|Conner-Department-Store",
1:"facility",
2:"34222",
3:"Conner-Department-Store",
index:0,
input:"facility=34222|Conner-Department-Store;"
length:4] */
solution2 = solution2[3].replace('-', ' ');
// "Conner Department Store"
}
I have applied some rules for the regex to work, feel free to modify them according your needs.
facility can be any Word built with alphabetical characters lower and uppercase (no other chars) at any length
= needs to be the char =
34222 can be any number but no other characters
| needs to be the char |
Conner-Department-Store can be any characters except one of the following (reserved delimiters): :/?#[]#;,'
Hope this helps :)
edit: to find only the part
facility=34222%7CConner-Department-Store; just modify the regex to
match facility= instead of ([A-z]*)=:
/(facility)=([0-9]*)\|(\S[^:\/?#\[\]\#\;\,']*)/
You can use cookies.js, a mini framework from MDN (Mozilla Developer Network).
Simply include the cookies.js file in your application, and write:
docCookies.getItem("Connor Department Store");

Finding the difference between two string in Javascript with regex [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 7 years ago.
Improve this question
Regex experts please help to see if this problem can be solved by regex:
Given string 1 is any string
And string 2 is any string containing all parts of string 1 (but not a simple match -- I will give example)
How to use regex to replace all parts of string 1 in string 2 with blank so that what's remained is the string not in string 1?
For example:
str1 = "test xyz";
str2 = "test ab xyz"
I want " ab" or "ab " back. What is the regex I can write so that when I run a replace function on str2, it will return " ab"?
Here is some non-regex code:
function findStringDiff(str1, str2) {
var compareString = function(str1, str2) {
var a1 = str1.split("");
var a2 = str2.split("");
var idx2 = 0;
a1.forEach(function(val) {
if (a2[idx2] === val) {
a2.splice(idx2,1);
} else {
idx2 += 1;
}
});
if (idx2 > 0) {
a2.splice(idx2,a2.length);
}
return a2.join("");
}
if (str1.length < str2.length) {
return compareString(str1, str2);
} else {
return compareString(str2, str1);
}
}
console.log(findStringDiff("test xyz","test ab xyz"));
Regexes only recognize if a string matches a certain pattern. They're not flexible enough to do comparisons like you're asking for. You would have to take the first string and build a regular language based on it to recognize the second string, and then use match groups to grab the other parts of the second string and concatenate them together. Here's something that does what I think you want in a readable way.
//assuming "b" contains a subsequence containing
//all of the letters in "a" in the same order
function getDifference(a, b)
{
var i = 0;
var j = 0;
var result = "";
while (j < b.length)
{
if (a[i] != b[j] || i == a.length)
result += b[j];
else
i++;
j++;
}
return result;
}
console.log(getDifference("test fly", "test xy flry"));
Here's a jsfiddle for it: http://jsfiddle.net/d4rcuxw9/1/
I find this question really interesting. Even though I'm a little late, I would like to share my solution on how to accomplish this with regex. The solution is concise but not very readable.
While I like it for its conciseness, I probably would not use it my code, because it's opacity reduces the maintainability.
var str1 = "test xyz",
str2 = "test ab xyz"
replacement = '';
var regex = new RegExp(str1.split('').map(function(char){
return char.replace(/[.(){}+*?[|\]\\^$]/, '\\$&');
}).join('(.*)'));
if(regex.test(str2)){
for(i=1; i<str1.length; i++) replacement = replacement.concat('$' + i);
var difference = str2.replace(regex, replacement);
} else {
alert ('str2 does not contain str1');
}
The regular expression for "test xyz" is /t(.*)e(.*)s(.*)t(.*) (.*)x(.*)y(.*)z/ and replacement is "$1$2$3$4$5$6$7".
The code is no longer concise, but it works now even if str1 contains special characters.
To find out if there are extra '.' like you are asking for, you can do this:
result = "$1...00".match(/\$1\.(\.*)?00/)[1];
result is then the EXTRA '.'s found. You cannot use regex to compare strings using only regex. Perhaps use this, then compare the results.
You can also try this:
result = "$1...00".match(/(\$)(\d+)\.(\.*)?(\d+)/);
// Outputs: ["$1...00", "$", "1", "..", "00"]
Which will extract the various parts to compare.
If you are only concerned with testing whether a given string contains two or more sequential dot '.' characters:
var string = '$1..00',
regexp = /(\.\.+)/;
alert('Is this regular expression ' + regexp + ' found in this string ' + string + '?\n\n' + regexp.test(string) + '\n\n' + 'Match and captures: ' + regexp.exec(string));
If you need it to match the currency format:
var string = '$1..00',
regexp = /\$\d*(\.\.+)(?:\d\d)+/;
alert('Is this regular expression ' + regexp + ' found in this string ' + string + '?\n\n' + regexp.test(string) + '\n\n' + 'Match and captures: ' + regexp.exec(string));
But I caution you that Regular Expressions aren't for comparing the differences between two strings; they are used for defining patterns to match against given strings.
So, while this may directly answer how to find the "multiple dots" pattern, it is useless for "finding the difference between two strings".
The StackOverflow tag wiki provides an excellent overview and basic reference for RegEx. See: https://stackoverflow.com/tags/regex/info

append single quotes to characters

I have a string like
var test = "1,2,3,4";
I need to append single quotes (' ') to all characters of this string like this:
var NewString = " '1','2','3','4' ";
Please give me any suggestion.
First, I would split the string into an array, which then makes it easier to manipulate into any form you want. Then, you can glue it back together again with whatever glue you want (in this case ','). The only remaining thing to do is ensure that it starts and ends correctly (in this case with an ').
var test = "1,2,3,4";
var formatted = "'" + test.split(',').join("','") + "'"
var newString = test.replace(/(\d)/g, "'$1'");
JS Fiddle demo (please open your JavaScript/developer console to see the output).
For multiple-digits:
var newString = test.replace(/(\d+)/g, "'$1'");
JS Fiddle demo.
References:
Regular expressions (at the Mozilla Developer Network).
Even simpler
test = test.replace(/\b/g, "'");
A short and specific solution:
"1,2,3,4".replace(/(\d+)/g, "'$1'")
A more complete solution which quotes any element and also handles space around the separator:
"1,2,3,4".split(/\s*,\s*/).map(function (x) { return "'" + x + "'"; }).join(",")
Using regex:
var NewString = test.replace(/(\d+)/g, "'$1'");
A string is actually like an array, so you can do something like this:
var test = "1,2,3,4";
var testOut = "";
for(var i; i<test.length; i++){
testOut += "'" + test[i] + "'";
}
That's of course answering your question quite literally by appending to each and every character (including any commas etc.).
If you needed to keep the commas, just use test.split(',') beforehand and add it after.
(Further explanation upon request if that's not clear).

How to evaluate "Who's on first?" as being equal to "whos on first." in JavaScript?

I need to evaluate two strings as being equal even if they have minor punctuation differences that would not make them different for the purposes of a Google search.
For example, these pairs would be considered equal (along with any other minor grammatical/spelling mistakes you can think might work in Google):
Who's on first?
whos on first.
Where's the beef/problem?
wheres the beef problem
Is there a library function in JavaScript that would do this?
This is actually not a simple task, to do it right you need to look up stemming.
This is a really naive way since it obviously doesn't handle a whole range of issues like misspellings:
var a = "some text totest....ok";
var b = "sometext totest ok";
function testRoughEquality(a, b) {
var ax = a.replace(/[^a-z]/gi, "");
var bx = b.replace(/[^a-z]/gi, "");
if(ax === bx)
{
alert('These strings were roughly the same: "' + a + '" and "' + b + '"');
}
return true;
};
The simplest answer is to remove characters that don't matter (the apostrophes and punctuation in your example), normalize other characters to word separators (the slash in your example), and downcase the lot.
var strs = ["Who's on first?","whos on first."];
for (var i=0,len=strs.length;i<len;++i){
strs[i] = strs[i].replace(/['?.]/g,'').replace(/[\/]/g,' ').toLowerCase();
}
console.log( strs[0] == strs[1] );
// true
"who's on First?".replace(/[\?' ]/g,'').toLowerCase()
Gets you closer, but it's not the best way to do it.
If it was only the punctuation and capitalisation issue (like the examples above), a simple solution would be to pass both through a regular expression to remove certain punctuation characters, then convert to lower case and compare.
Something like:
function stringCompare(str1, str2)
{
var test = /[\?\'\/]/g;
var s1 = str1.replace(test,"").toLowerCase();
var s2 = str2.replace(test,"").toLowerCase();
if(str1 === str2) { return true; }
return false;
}

Categories

Resources