split a string from end till second space - javascript

I have a string i want to split it so that I can extract the name from the particular string.
let str = "CN=John Mcclau - i0c00cu,OU=PET_Associates,OU=Users,OU=PET,DC=officecabs,DC=SAT-PET,Dt=com";
let splitstr= str.substr(3, str.indexOf(' -'))
console.log(splitstr)
Sample str2 = "PN=Coey PT - ljooys4,OU=PET_Associates,OU=Users,OU=PET,DC=officecabs,DC=SAT-PET,Dt=com";
I am doing this way but it displays the " - " too. How can i fix it?

You can split twice, first on the '=' and taking the second index then on the '-' and taking the first index. Add a trim() and you're good to go
const getName = str => str.split('=')[1].split('-')[0].trim();
let str = "CN=John Mcclau - i0c00cu,OU=PET_Associates,OU=Users,OU=PET,DC=officecabs,DC=SAT-PET,Dt=com";
console.log(getName(str))
str2 = "PN=Coey PT - ljooys4,OU=PET_Associates,OU=Users,OU=PET,DC=officecabs,DC=SAT-PET,Dt=com";
console.log(getName(str2))

If you switch out substr() for slice() it works fine using the same start/end indices
const getName = str => str.slice(3, str.indexOf(' -'));
const str ='CN=John Mcclau - i0c00cu,OU=PET_Associates,OU=Users,OU=PET,DC=officecabs,DC=SAT-PET,Dt=com',
str2 = "PN=Coey PT - ljooys4,OU=PET_Associates,OU=Users,OU=PET,DC=officecabs,DC=SAT-PET,Dt=com";
[str,str2].forEach(s=> console.log(getName(s)))

Related

What is the regex to remove last + sign from a string

I'm trying to generate a link using jQuery and need to trim the last '+' sign off the end. Is there a way to detect if there is one there, and then trim it off?
So far the code removes the word 'hotel' and replaces spaces with '+', I think I just need another replace for the '+' that shows up sometimes but not sure how to be super specific with it.
var nameSearch = name.replace("Hotel", "");
nameSearch = nameSearch.replace(/ /g, "+");
The answer to
What is the regex to remove last + sign from a string
is this
const str = "Hotel+"
const re = /\+$/; // remove the last plus if present. $ is "end of string"
console.log(str.replace(re,""))
The question is however if this is answering the actual problem at hand
If you have the string
"Ritz Hotel"
and you want to have
https://www.ritz.com
then you could trim the string:
const fullName = "Ritz Hotel",
name = fullName.replace("Hotel", "").trim().toLowerCase(),
link = `https://www.${name}.com`;
console.log(link)
// or if you want spaces to be converted in url safe format
const fullName1 = "The Ritz Hotel",
name1 = fullName1.replace("Hotel", "").trim().toLowerCase(),
link1 = new URL(`https://www.hotels.com/search?${name1}`).toString()
console.log(link1)
As an alternative to mplungjan's answer, you can use str.endsWith() for the check. If it ends on the + it will be cut out. There is no need for regex. If you can avoid regex you definitely should.
let str = "Hotel+";
if (str.endsWith("+")) {
str = str.substr(0, str.length - 1);
}
console.log(str);
Below you can find a function to replace all the whitespace characters with + excluding the last one:
const raw = "My Ho te l ";
function replaceSpacesWithPlus(raw) {
let rawArray = Array.from(raw);
let replArray = [];
for (let i = 0; i < rawArray.length; i++) {
const char = rawArray[i];
// handle characters 0 to n-1
if (i < rawArray.length - 1) {
if (char === ' ') {
replArray.push('+');
} else {
replArray.push(char);
}
} else {
// handle last char
if (char !== ' ' && char !== '+') {
replArray.push(char);
}
}
}
return replArray;
}
console.log(replaceSpacesWithPlus(raw));
The below snippet will remove all the existing + symbols from string.
let str = 'abcd + efg + hij';
str = str.replace(/\+/gm, '');
//output: abcd efg hij
For trim use the below snippet. It will remove the spaces from around the string.
let str = " Hello World!! "
str = str.trim();
// output: Hello World!!
If you want to replace the last + symbol only.
let str = 'abcd + efg + hij';
let lastIndex = str.lastIndexOf('+');
if (lastIndex > -1) {
let nextString = str.split('');
nextString.splice(lastIndex, 1, '');
str = nextString.join('');
}
// output: abcd + efg hij

Split a string at the first occurence of a string using Javascript

I've tried multiple solutions from other threads but nothing seems to work when the split flag is a string as well. In this case I need to separate the first " - " (space dash space) from the rest of the string, which contains other occurences of " - "
var string = "1 - 000 : 3 - loremipsum";
Looking for a resulting array of:
[1][000 : 3 - loremipsum]
Simple replace() will suffice if you want that expected output
var str = "1 - 000 : 3 - loremipsum"
console.log('['+str.replace(' - ', '][')+']')
You can split by " - " to get an array of the form:
["1", "000 : 3", "loremipsum"]
Then you can use destructuring assignment to separate the first element and the rest of the array (r) from each other, and use a template literal to form a string, with the rest of the array (r) joined back together with a hyphen:
const string = "1 - 000 : 3 - loremipsum";
const [first, ...r] = string.split(" - ");
const res = `[${first}][${r.join(" - ")}]`;
console.log(res);
Or if you want your result in an array, you can create an new array rather than using a template literal:
const string = "1 - 000 : 3 - loremipsum";
const [first, ...r] = string.split(" - ");
const res = [first, r.join(" - ")];
console.log(res);
You can try using substrings since you seem to be a beginner in javascript.
var string = "1 - 000 : 3 - loremipsum";
var start = string.indexOf(" - "); // find the first ocurance of space dash space
var result = [];
result.push(string.substr(0, start)); // string before " - "
result.push(string.substr(start+3)); // string after " - "
console.log(result);
You could split on your delimiter and then join all the elements after the first element:
const string = "1 - 000 : 3 - loremipsum"
const delimiter = " - "
const splitArray = string.split(delimiter)
const firstElement = splitArray[0]
const otherElementsJoined = splitArray.slice(1).join(delimiter)
const finalArray = [firstElement, otherElementsJoined]
console.log(finalArray)
You could try using match() here:
var string = "1 - 000 : 3 - loremipsum";
var first = string.match(/^(.*?) -/)[1];
var second = string.match(/^.*? - (.*)$/)[1];
var output = [first, second];
console.log(output);

Javascript - Regex to replace last 4 digit

I have a number variable at JavaScript and i want it replaced in last 4 character. Example:
I have a number 123456789 and i want it to be replaced like this 12345****
Is there any regex to do that in JavaScript?
Use replace() with regex /\d{4}$/
var res = '123456789'.replace(/\d{4}$/, '****');
document.write(res);
Regex explanation
Or using substring() or substr()
var str = '123456789',
res = str.substr(0, str.length - 4) + '****';
document.write(res);
You could use substring as well:
var s = '123456789';
var ns = s.substring(0, s.length - 4) + '****';
document.write(ns);

javascript - count spaces before first character of a string

What is the best way to count how many spaces before the fist character of a string?
str0 = 'nospaces even with other spaces still bring back zero';
str1 = ' onespace do not care about other spaces';
str2 = ' twospaces';
Use String.prototype.search
' foo'.search(/\S/); // 4, index of first non whitespace char
EDIT:
You can search for "Non whitespace characters, OR end of input" to avoid checking for -1.
' '.search(/\S|$/)
Using the following regex:
/^\s*/
in String.prototype.match() will result in an array with a single item, the length of which will tell you how many whitespace chars there were at the start of the string.
pttrn = /^\s*/;
str0 = 'nospaces';
len0 = str0.match(pttrn)[0].length;
str1 = ' onespace do not care about other spaces';
len1 = str1.match(pttrn)[0].length;
str2 = ' twospaces';
len2 = str2.match(pttrn)[0].length;
Remember that this will also match tab chars, each of which will count as one.
You could use trimLeft() as follows
myString.length - myString.trimLeft().length
Proof it works:
let myString = ' hello there '
let spacesAtStart = myString.length - myString.trimLeft().length
console.log(spacesAtStart)
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/TrimLeft
str0 = 'nospaces';
str1 = ' onespace do not care about other spaces';
str2 = ' twospaces';
arr_str0 = str0.match(/^[\s]*/g);
count1 = arr_str0[0].length;
console.log(count1);
arr_str1 = str1.match(/^[\s]*/g);
count2 = arr_str1[0].length;
console.log(count2);
arr_str2 = str2.match(/^[\s]*/g);
count3 = arr_str2[0].length;
console.log(count3);
Here:
I have used regular expression to count the number of spaces before the fist character of a string.
^ : start of string.
\s : for space
[ : beginning of character group
] : end of character group
str.match(/^\s*/)[0].length
str is the string.

Parse complex string with one regular expression

How can I get from this string
genre:+Drama,Comedy+cast:+Leonardo+DiCaprio,Cmelo+Hotentot+year:+1986-1990
this
genre: [Drama, Comedy],
cast: [Leonardo DiCaprio, Cmelo Hotentot],
year: [1986-1990]
with one regular expression?
This could be done using one regex and overload of replace function with replacer as a second argument. But honestly, I have to use one more replace to get rid of pluses (+) - I replaced them by a space () char:
var str = 'genre:+Drama,Comedy+cast:+Leonardo+DiCaprio,Cmelo+Hotentot+year:+1986-1990';
str = str.replace(/\+/g, ' ');
var result = str.replace(/(\w+:)(\s?)([\w,\s-]+?)(\s?)(?=\w+:|$)/g, function (m, m1, m2, m3, m4, o) {
return m1 + ' [' + m3.split(',').join(', ') + ']' + (o + m.length != str.length ? ',' : '') + '\n';
});
You could find the full example on jsfiddle.
You will not get them into arrays from the start, but it can be parsed if the order stays the same all the time.
var str = "genre:+Drama,Comedy+cast:+Leonardo+DiCaprio,Cmelo+Hotentot+year:+1986-1990";
str = str.replace(/\+/g," ");
//Get first groupings
var re = /genre:\s?(.+)\scast:\s?(.+)\syear:\s(.+)/
var parts = str.match(re)
//split to get them into an array
var genre = parts[1].split(",");
var cast = parts[2].split(",");
var years = parts[3];
console.log(genre);
You can't do this using only regular expressions cause you're trying to parse a (tiny) grammar.

Categories