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 4 months ago.
Improve this question
First part:
I want to replace the spaces in a string to \n but the first space I want it to be replaced with a double like this: \n\n
var string = "this is something random “
Result needed:
var string = "this\n\nis\nsomething\nrandom\n"
Second part:
I want to replace the string quotes with backticks.
var string = "this\n\nis\nsomething\nrandom\n"
Result needed:
var string = `this\n\nis\nsomething\nrandom\n`
First Part
For what you want, you can just call a replace function to replace the first occurrence, then a replaceAll/regex to replace all others:
let input = "Hello World !"
function replaceFirstThenAll(string, lookfor, replace) {
return string
// replace the first occurance
.replace(lookfor, replace.repeat(2))
// now all others
.replace(new RegExp(lookfor, 'g') /* global regex */, replace)
}
console.log(replaceFirstThenAll(
input,
" ",
"\n"
)) // Hello\n\nWorld\n !
Second Part
The way that you declare a string doesn't matter in js, so there's no way to replace it. No matter which method you use, the string is the same.
"String1" == 'String1' // true
'String2' == `String2` // true
Related
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 2 years ago.
Improve this question
I'll make this extremely simple
I have a function that comes across a string as such by design: water 'thing one'
I need to split this string by the first space, since there are spaces elsewhere.
I've tried many regex expressions like / .*? /, but they can only match two consecutive spaces.
How do I do this?
Thanks in advance.
If you just want the portion of the string before and after the first space, you could use regex replacement here:
var input = "water 'thing one'";
var first = input.replace(/[ ].*$/, "");
var second = input.replace(/^\S*[ ]/, "");
console.log("first part: " + first);
console.log("second part: " + second);
You can capture them using String#match with this regex:
/(.*?) (.*)/
const text = "water 'thing one'";
const [, first, second] = text.match(/(.*?) (.*)/);
console.log('first:', first);
console.log('second:', second);
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 2 years ago.
Improve this question
I'm trying to parse strings to find and replace # mentions.
Here is a sample string:
Hi #jordan123 and #jordan have a good day
I want to find and replace #jordan with #jordananderson without modifying #jordan123
I used this regex to find a list of all of the mentions in the string:
let string = 'Hi #jordan123 and #jordan have a good day'
let result = string.match(/\B\#\w\w+\b/g);
that returns:
['#jordan123', '#jordan']
But I can't figure out how to continue and complete the replacement.
Valid characters for the username are alphanumeric and always start with the # symbol.
So it also needs to work for strings like this:
Hi #jordan123 and #jordan!! have a good day
And this
Hi #jordan123! and !#jordan/|:!! have a good day
My goal is to write a function like this:
replaceUsername(string, oldUsername, newUsername)
If I understand your question correctly, you need \b, which matches a word boundary:
The regex: #jordan\b will match:
Hi #jordan123 and #jordan!! have a good day
Hi #jordan123! and !#jordan/|:!! have a good day
To build this regex, just build it like a string; don't forget to sanitize the input if it's from the user.
var reg = new RegExp("#" + toReplace + "\\b")
In general if you have one string of a found value, and a larger string with many values, including the found value, you can use methods such as split, replace, indexOf and substring etc to replace it
The problem here is how to replace only the string that doesn't have other things after it
To do this we can first look for indexOf the intended search string, add the length of the string, then check if the character after it doesn't match a certain set of characters, in which case we set the original string to the substring of the original up until the intended index, then plus the new string, then plus the substring of the original string starting from the length of the search string, to the end. And if the character after the search string DOES match the standard set of characters, do nothing
So let's try to make a function that does that
function replaceSpecial(original, search, other, charList) {
var index= original.indexOf(search)
if(index > -1) {
var charAfter = original [index + search.length]
if (!charList.includes(charAfter)) {
return original. substring (0, index) + other + original. substring (index+ search.length)
} else return original
} else return original
}
Then to use it with our example
var main ="Hi #jordan123 and #jordan!! have a good day"
var replaced = replaceSpecial (main, "#jordan", "#JordanAnderson", [0,1,2,3,4,5,6,7,8,9])
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 3 years ago.
Improve this question
I'm wondering how to show the first two characters and replace all last character of a string by symbol *.
Ex: 121,121,121 -> 12x,xxx,xxx .
Thanks
I love using regex when it comes to replace string according to some pattern.
var p = '121,121,121';
var regex = /(?<=.{2})([0-9])/gm;
console.log(p.replace(regex, 'x'));
You can use substring and regular expression. See the sample below.
var str = "121,121,121";
var res = str.substring(0, 2) + '' + str.substring(2, str.length).replace(/[0-9]/g,"x");
alert(res);
Just use substring and replace with a simple regex (to single out digits and keep commas and other punctuation):
const str = "121,121,121";
const obfuscated = `${str.substring(0, 2)}${str.substring(2).replace(/\d/g, "*")}`;
console.log(obfuscated);
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 4 years ago.
Improve this question
I want to allow 3 characters 1st Underscore (_) , 2nd hyphen (-) 3rd Dot (.)
but i want to put conditions that only one character is allowed at a time from all of them, and also only one time.
e.g
allowed usernames = abc.def , abc-def , abc_def
not allowed usernames = abc.de.f alert here(only one special character is allowed in a username)
not allowed usernames = abc.de-f , abc.de_f , ab-cd_ef
What should i do.
Try /^[a-z]*[-._]?[a-z]*$/
var tests = ['abc.def', 'abc-def', 'abc_def', 'abc.de.f','abc.de-f' , 'abc.de_f', 'ab-cd_ef'];
$.each(tests, function(a,b) {
$('body').append('<div>' + b + ' = ' + regIt(b) + '</div>');
});
function regIt(str) {
return /^[a-z]*[-._]?[a-z]*$/.test(str);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
^[a-z]*([-._]?)(?:[a-z]|\1)*$
This regex will match letters until it reaches the end of the string. If it reaches a symbol (- . or _) it will store that symbol as group 1, and keep matching for letters or that same symbol until the end of the string.
The following are matching examples:
an empty string
_something
something-something
foo_bar_baz
foo.
And here are some invalid strings:
my_file.txt
alpha.bravo_charlie
not-working_
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 8 years ago.
Improve this question
How can I add a character after the second characters in string?
Ex: I want this : 1700 to become this: 17:00.
The simplest way, in my opinion, is using substr to split the string and concatenate the other character in between. This will work no matter the length of the second part:
var str = "1700";
str.substr(0,2)+":"+str.substr(2);
this would do the magic:
"1700".replace(/(..)$/, ":$1")
alternative you can do something like look from behind in substr too like:
var string = "1700";
string = string.substr(0, string.length -2) + ":" + string.substr(-2, 2);
they both also work on something like: 900 wich will turn into 9:00
the regex and the substr line both do the same. if you want readability i'd consider the regex.
You could do this:
'1700'.match(/../g).join(':')
The following regexp accepts 3+ chars:
'700'.match(/^(.+)(..)$/).slice(1, 3).join(':') // "7:00"
Shortest and probably fastest solution:
s[0]+s[1]+":"+s[2]+s[3]
Without using regexp, you can use substr --
string = string.substr(0,2) + ":" + string.substr(2);
You can use substring. Consider the following:
string1 = "1700";
string2 = ":";
string1 = string1.substring(0,2) + string2 + string1.substring(2);
alert(string1);