Reputation: 1978
how can i get the index of matching pattern in the string using javascript?
consider string original_string = "i am [1@some user] some more text [2@another user]"
i am using pattern /[\d+@(?[^]\r\n]*)]/g to match strings in square brackets
then i use string.matchAll(original_string) to get the matches
const matches = string.matchAll(original_string);
let names = [];
for (const match in matches) {
names.push(match);
}
now the names array will contain ["some user", "another user"]
now how do i get the index of the first match in original string from names array.
const final_string = []
const original_string = "i am [12@some user] some text [2@some user2]"
let prev_match_pos = 0
for each match in original_string
final_string.push(text from the end of prev match up until current
match start)
final_string.push(<span>match</span>)
update prev_match_pos
final_string.push(text from the end of previous match to the end of the
original string)
I want to implement the above algorithm in javascript.
Basically i want to convert this string "i am [1@some user] some more text [2@another user]"
to
"i am <span>some user</span>
some more text `another user'"
how can i do it?
the basic implementation is as below,
get the strings in brackets. from the string in brackets extract value after @ character. then embed the extracted value in span tag and place them in the original string.
could someone help me with this. thanks.
Upvotes: 1
Views: 698
Reputation: 196
don't really know if this can help you but a quick solution could be:
HTML:
<div>
<p>user 1 : <span id="first"></span></p>
<p>user 2: <span id="second"></span></p>
</div>
<script>
let string = "first user is [1@user1] and second is [2@user2]";
let users = string.match(/[^[\]]+(?=])/g).map(el => el.split('@')[1]);
document.getElementById('first').innerText = users[0];
document.getElementById('second').innerText = users[1];
</script>
Upvotes: 0
Reputation: 1038
You will need to improve the regex, this works well to for the given example,
let originalString = "i am [1@some user] some more text [2@another user]";
const matches = originalString.match(/[^[\]]+(?=])/g);
let newString = originalString;
matches.forEach(match => {
newString = newString.replace(
`[${match}]`,
`<span>${match.split("@")[1]}</span>`
);
});
console.log(newString);
Upvotes: 1
Reputation: 2150
If you want to replace the [id@name]
portion with the formatted name (e.g. <span>name</span>
), you can use String.replace.
const text = 'i am [1@some user] some more text [2@another user]';
text.replace(/\[\d+@([A-z\s]*)\]/g, '<span>$1</span>');
// outputs: i am <span>some user</span> some more text <span>another user</span>
String.replace
supports using capture groups in the newSubstr
parameter (new substring).
Upvotes: 1