Regex to replace colon in JS - javascript

I have the following string:
let str = '/user/:username/'
I want to extract replace username with harry with colon removed.
I tried the following:
const regex = /[^:]+(?=:)/g
str.replace(regex, x => console.log(x))

Try: /:\w+/
let str = '/user/:username/'
str.replace(/:\w+/, "harry")
// => "/user/harry/"

let str = '/user/:username/';
let html = str.replace(":username", "harry");
console.log(html);

var str = '/user/:username/';
var newstr = str.replace(/:username/i, "harry");
print(newstr);
hi pal, is this what you are looking for? i found it at https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/String/replace

you can use like that :
let str = '/user/:username/';
str.replace(':username','harry')
// o/p => /user/harry/"

In your regex [^:]+(?=:) you are matching 1+ times not a colon and assert that at the end there should be a colon resulting in a match for /user/
If you want to use the negated character class you could match a colon and then not a forward slash:
:[^\/]+
const str = `/user/:username/`;
const result = str.replace(/:[^\/]+/, "harry");
console.log(result);

Related

Regex match for string between / and .jsp

If I do regex match for
str = "/mypage/account/info.jsp"
str.match('\/.*\.jsp')
I get entire string but I want to grab only "info"
How can I accomplish using only regex?
First, you can get the text after the last /
/[^/]*$/
and then get the desired result using split
const str = "/mypage/account/info.jsp";
const match = str.match(/[^/]*$/);
const result = match && match[0].split(".")[0];
console.log(result);
only regex
const str = "/mypage/account/info.jsp";
const match = str.match(/[^/]+(?=\.jsp$)/);
console.log(match[0]);

Regex to extract text from a string

Given the following string:
const myString = "This is my comment content. [~firstName.lastName]";
What is a javascript regex to extract the "firstName" and "lastName"?
What is a javascript regex to extract the content minus the "[~firstName.lastName]"?
I'm rubbish with Regex.
const myString = "This is my comment content. [~firstName.lastName]";
const first = myString.match(/.*\~(.*)\./)[1]
const last = myString.match(/.*\.(.*)]/)[1]
const both = myString.match(/.*\~(.*)\]/)[1]
console.log(first)
console.log(last)
console.log(both)
Here's a good website for regex help
You can try this-
let myString = "This is my comment content. [~firstName.lastName] and the original name is [~John.Doe]";
const regex = /\[~([^\]]+)\.([^\]]+)\]/g;
let match = regex.exec(myString);
const names = [];
while(match !== null) {
names.push({firstName: match[1], lastName: match[2]});
match = regex.exec(myString);
}
// Remove the pattern from the original string.
myString = myString.replace(regex, '');
console.log(names, myString);
This code will find all the matches found for the pattern.
You could target each name separately. match will return the complete match as the first element of the array, and the groupings specified by the ( and ) in the regex as the subsequent elements.
const str = 'This is my comment content. [~firstName.lastName]';
const regex = /\[~(.+)\.(.+)\]/;
console.log(str.match(regex));
Or you could target just the characters within the brackets and then split on the ..
const str = 'This is my comment content. [~firstName.lastName]';
const regex = /\[~(.+)\]/;
console.log(str.match(regex)[1].split('.'));

Remove part of the string before the FIRST dot with js

I have the next problem. I need to remove a part of the string before the first dot in it. I've tried to use split function:
var str = "P001.M003.PO888393";
str = str.split(".").pop();
But the result of str is "PO888393".
I need to remove only the part before the first dot. I want next result: "M003.PO888393".
Someone knows how can I do this? Thanks!
One solution that I can come up with is finding the index of the first period and then extracting the rest of the string from that index+1 using the substring method.
let str = "P001.M003.PO888393";
str = str.substring(str.indexOf('.')+1);
console.log(str)
You can use split and splice function to remove the first entry and use join function to merge the other two strings again as follows:
str = str.split('.').splice(1).join('.');
Result is
M003.PO888393
var str = "P001.M003.PO888393";
str = str.split('.').splice(1).join('.');
console.log(str);
You could use a regular expression with .replace() to match everything from the start of your string up until the first dot ., and replace that with an empty string.
var str = "P001.M003.PO888393";
var res = str.replace(/^[^\.]*\./, '');
console.log(res);
Regex explanation:
^ Match the beginning of the string
[^\.]* match zero or more (*) characters that are not a . character.
\. match a . character
Using these combined matches the first characters in the string include the first ., and replaces it with an empty string ''.
calling replace on the string with regex /^\w+\./g will do it:
let re = /^\w+\./g
let result = "P001.M003.PO888393".replace(re,'')
console.log(result)
where:
\w is word character
+ means one or more times
\. literally .
many way to achieve that:
by using slice function:
let str = "P001.M003.PO888393";
str = str.slice(str.indexOf('.') + 1);
by using substring function
let str = "P001.M003.PO888393";
str = str.substring(str.indexOf('.') + 1);
by using substr function
let str = "P001.M003.PO888393";
str = str.substr(str.indexOf('.') + 1);
and ...

Regex to remove all "" and []

I have a string like this:
const myString = "["dupa", "dupa", "dupa"]";
how to use regex in JS/TS to remove all characters " and [ and ]?
i need only dupa, dupa, dupa
thanks for any help
It will return you string with other removed from it and with your double quoted there is problem with it. So use single quote.
const myString = '["dupa", "dupa", "dupa"]';
const a = myString.replace(/[\[\]']+/g, '').replace(/"/g, '');
console.log(a);
You will get "dupa, dupa, dupa"
Or you can go with :
const myString = '["dupa", "dupa", "dupa"]';
const a = JSON.parse(myString);
console.log(a.join(", "))

How to add a character to the beginning of every word in a string in javascript?

I have a string for example
some_string = "Hello there! How are you?"
I want to add a character to the beginning of every word such that the final string looks like
some_string = "#0Hello #0there! #0How #0are #0you?"
So I did something like this
temp_array = []
some_string.split(" ").forEach(function(item, index) {
temp_array.push("#0" + item)
})
console.log(temp_array.join(" "))
Is there any one liner to do this operation without creating an intermediary temp_array?
You could map the splitted strings and add the prefix. Then join the array.
var string = "Hello there! How are you?",
result = string.split(' ').map(s => '#0' + s).join(' ');
console.log(result);
You could use the regex (\b\w+\b), along with .replace() to append your string to each new word
\b matches a word boundry
\w+ matches one or more word characters in your string
$1 in the .replace() is a backrefence to capture group 1
let string = "Hello there! How are you?";
let regex = /(\b\w+\b)/g;
console.log(string.replace(regex, '#0$1'));
You should use map(), it will directly return a new array :
let result = some_string.split(" ").map((item) => {
return "#0" + item;
}).join(" ");
console.log(result);
You could do it with regex:
let some_string = "Hello there! How are you?"
some_string = '#0' + some_string.replace(/\s/g, ' #0');
console.log(some_string);
The simplest solution is regex. There is already regex soln give. However can be simplified.
var some_string = "Hello there! How are you?"
console.log(some_string.replace(/[^\s]+/g, m => `#0${m}`))
const src = "floral print";
const res = src.replace(/\b([^\s]+)\b/g, '+$1');
result is +floral +print
useful for mysql fulltext boolean mode search.

Categories